Spring/Spring 문법

Spring Security 커스컴하여 formLogin // loginProcessingUrl

열심히 해 2024. 10. 11. 17:51

 

@Configuration
@EnableWebSecurity // Spring Security 지원을 가능하게 함
public class WebSecurityConfig {

    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        // CSRF 설정
        http.csrf((csrf) -> csrf.disable());

        http.authorizeHttpRequests((authorizeHttpRequests) ->
                authorizeHttpRequests
                        .requestMatchers(PathRequest.toStaticResources().atCommonLocations()).permitAll() // resources 접근 허용 설정
                        .requestMatchers("/api/user/**").permitAll() // '/api/user/'로 시작하는 요청 모두 접근 허가
                        .anyRequest().authenticated() // 그 외 모든 요청 인증처리
        );

        // 로그인 사용, default 가 아닌 custom
        http.formLogin((formLogin) ->
                formLogin
                        .loginPage("/api/user/login-page") // 로그인 View 제공 (GET /api/user/login-page)
                        .loginProcessingUrl("/api/user/login") // 로그인 처리 (POST /api/user/login)
                        .defaultSuccessUrl("/") // 로그인 성공 시 URL
                        .failureUrl("/api/user/login-page?error") // 로그인 실패 시 URL
                        .permitAll()
        );

        return http.build();
    }
}

 

 

 

Controller 

@GetMapping("/api/user/login-page")
public String loginPage() {
    return "login";
}

 

 

똑같은 url : /api/user/login-page 가

 

Spring Security Filter 와 Controller 에 들어있습니다.

 

 /api/user/login-page 가 의미하는 바는 다릅니다. 

 

전자의  /api/user/login-page 는 컨트롤러를 가기 전단계의 url로서 존재하고,

 

후자의  /api/user/login-page 는 전자의 과정을 통과한 후의 url 을 의미합니다.

 

Filter 에서 로그인이 성공하였다고 Controller 로 가는 것이 아닙니다. 

 

tells Spring Security to process the submitted credentials when sent the specified path and, by default, redirect user back to the page user came from. It will not pass the request to Spring MVC and your controller.

Spring Security가 지정된 경로를 전송할 때 제출된 자격 증명을 처리하고 기본적으로 사용자를 사용자가 보낸 페이지로 다시 리디렉션하도록 합니다. 요청이 Spring MVC와 컨트롤러에 전달되지 않습니다.

 

 

참고 : 

 

https://sooyeon-surf.tistory.com/22