Как настроить собственную страницу входа для Java-сервера Spring BootJAVA

Программисты JAVA общаются здесь
Anonymous
Как настроить собственную страницу входа для Java-сервера Spring Boot

Сообщение Anonymous »

Проблема:
При настройке простого HTTP-сервера Java я получаю ошибки CSRF от SpringBootSecurity при предоставлении собственной страницы входа
Что я могу сделать? Я пытаюсь сделать страницу входа, которая запрашивает учетные данные, из моего собственного файла login.html, найденного по адресу src/main/resources/static/login.html

*Меня перенаправляют обратно на страницу входа. бесконечно из-за ошибки CSRF.
Ниже приведены фрагменты формы входа и ее сценария, а также SecurityConfig, список зависимостей приложения Spring Boot и выходные данные отладки при попытке доступа к веб-страница.
Как я могу отредактировать ее, чтобы приложение Springboot загружало страницу входа из моего собственного статического ресурса, а не из настроек по умолчанию?
< strong>Проблемная часть кода:

Код: Выделить всё

.formLogin(login -> login
.loginPage("/login.html") // Serve static login page
.loginProcessingUrl("/perform_login")
.defaultSuccessUrl("/index.html", true)
Я пробовал:


настроить .loginForm("/login .html"), закомментировав строку. результатом является перенаправление на встроенную страницу входа в Springboot, аутентификация успешна
B
Удаление .loginForm("/login.html") и . loginProccesingUrl("/index.html")
Но я столкнулся с ошибкой, которая вызывает слишком много перенаправлений, и мне заблокирован доступ к контенту
Но Кажется, я получаю постоянную ошибку CSRF.

Временное исправление — комментирование .loginForm("/login.html")
в настоящее время он загружает мою пользовательскую страницу входа в систему, получает ошибку csrf и перенаправляет на встроенную страницу входа в SpringBoot, где я успешно авторизуюсь и получаю доступ к index.html
Я пробовал несколько настроек с SecurityFilterChain, но мне не удалось получить доступ без получения ошибки в csrf. Я хочу использовать только свой логин.html

Код: Выделить всё

2024-09-15T13:08:13.653+03:00 DEBUG 161892 --- [Page Displayer] [.0-65002-exec-6] o.s.security.web.FilterChainProxy        : Securing GET /login
2024-09-15T13:08:17.285+03:00 DEBUG 161892 --- [Page Displayer] [.0-65002-exec-7] o.s.security.web.FilterChainProxy        : Securing POST /login
2024-09-15T13:08:17.286+03:00 DEBUG 161892 --- [Page Displayer] [.0-65002-exec-7] o.s.security.web.csrf.CsrfFilter         : Invalid CSRF token found for http://{MyIP}:65002/login
2024-09-15T13:08:17.287+03:00 DEBUG 161892 --- [Page Displayer] [.0-65002-exec-7] o.s.s.w.access.AccessDeniedHandlerImpl   : Responding with 403 status code
2024-09-15T13:08:17.292+03:00 DEBUG 161892 --- [Page Displayer] [.0-65002-exec-7] o.s.security.web.FilterChainProxy        : Securing POST /error
2024-09-15T13:08:17.292+03:00 DEBUG 161892 --- [Page Displayer] [.0-65002-exec-7] o.s.s.w.a.AnonymousAuthenticationFilter  : Set SecurityContextHolder to anonymous SecurityContext
2024-09-15T13:08:17.293+03:00 DEBUG 161892 --- [Page Displayer] [.0-65002-exec-7] o.s.s.web.DefaultRedirectStrategy        : Redirecting to http://{MyIP}:65002/login
2024-09-15T13:08:17.307+03:00 DEBUG 161892 --- [Page Displayer] [.0-65002-exec-8] o.s.security.web.FilterChainProxy        : Securing GET /login

Восстановите проблему:
Шаг 1. Настройка проекта Spring Boot
Создайте новый проект Spring Boot со следующими зависимостями:

Код: Выделить всё


org.springframework.boot
spring-boot-starter-data-jpa


org.springframework.boot
spring-boot-starter-security


org.springframework.boot
spring-boot-starter-web


com.h2database
h2
runtime


org.springframework.boot
spring-boot-starter-test
test


Шаг 2. Создайте статическую страницу входа
Разместите собственную страницу входа в src/main/resources/static/login.html. Убедитесь, что действие формы соответствует вашему SecurityConfig.

Код: Выделить всё



Login

document.addEventListener("DOMContentLoaded", function () {
fetch('/csrf')
.then(response => response.json())
.then(data => {
const csrfInput = document.createElement('input');
csrfInput.type = 'hidden';
csrfInput.name = data.parameterName;
csrfInput.value = data.token;
document.querySelector('form').appendChild(csrfInput);
document.querySelector('input[type="submit"]').disabled = false;
});
});





Username


Password








Шаг 3. Настройте безопасность входа в систему

Код: Выделить всё

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;
import org.springframework.security.web.SecurityFilterChain;

@Configuration
public class SecurityConfig {

@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
http
.authorizeHttpRequests((requests) -> requests
// Allow access to static resources without authentication
.requestMatchers("/js/**", "/style/**", "/images/**", "/style/**",
"/backgrounds/**", "/icons/**")
.permitAll()
// Allow access to the login page without auth
.requestMatchers("/login.html", "/logout").permitAll()
// Protect all other requests
.anyRequest().authenticated() // All other requests require
// authentication
)
.formLogin(login -> login
// .loginPage("/login.html") // Serve static login page
.loginProcessingUrl("/perform_login")
.defaultSuccessUrl("/index.html", true) // Redirect to index.html after
// successful login
.permitAll() // Allow everyone to access the login page
)
.logout(logout -> logout
.logoutUrl("/login") // Custom logout URL
.logoutSuccessUrl("/login?logout") // Redirect to login page after logout
.invalidateHttpSession(true) // Invalidate session
.deleteCookies("JSESSIONID") // Delete session cookie
.permitAll() // Allow logout without authentication
);
return http.build();
}

Шаг 4. Создайте базовый контроллер
Добавьте простой контроллер для обслуживания статических страниц и обработки перенаправлений.

Код: Выделить всё

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;

@Controller
public class PageController {

@GetMapping("/index.html")
public String index() {
return "index.html"; // Serve index.html from static resources
}
@GetMapping("/logout")
public String logout(HttpSession session) {
session.invalidate(); // Invalidate the session to log the user out
return "redirect:/"; // Redirect to the home page (or login page)
}
}

Шаг 5. Запустите приложение локально ./mvnw Spring-boot::run

Подробнее здесь: https://stackoverflow.com/questions/789 ... ava-server

Вернуться в «JAVA»