[스프링 시큐리티] 3. 스프링 시큐리티 기본 API 및 Filter 이해 - Form Login 인증

Jimin·2023년 6월 30일

스프링 시큐리티

목록 보기
4/7
post-thumbnail

  • http.formLogin() // Form 로그인 인증 기능이 작동함
protected void configure(HttpSecurity http) throws Exception {
	http.formLogin()
		.loginPage(/login.html") // 사용자 정의 로그인 페이지
		.defaultSuccessUrl("/home) // 로그인 성공 후 이동 페이지
		.failureUrl("/login.html?error=true) // 로그인 실패 후 이동 페이지
		.usernameParameter("username") // 아이디 파라이터명 설정
		.passwordParameter(“password”) // 패스워드 파라미터명 설정
		.loginProcessingUrl(/login") // 로그인 Form Action Url
		.successHandler(loginSuccessHandler()) // 로그인 성공 후 핸들러 
		.failureHandler(loginFailureHandler()) // 로그인 실패 후 핸들러
}

  • 실제 코드에 적용
@Configuration
public class SecurityConfig {

    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        http
                .authorizeHttpRequests((authz) -> authz
                        .anyRequest().authenticated()
                )
                .httpBasic(withDefaults());

        http
                .formLogin()
                .loginPage("/loginPage")   // 사용자 정의 로그인 페이지
                .defaultSuccessUrl("/") // 로그인 성공 후 이동 페이지
                .failureUrl("/login") // 로그인 실패 후 이동 페이지
                .usernameParameter("userId") // 아이디 파라미터명 설정
                .passwordParameter("passwd") // 패스워드 파라미터명 설정
                .loginProcessingUrl("/login_proc") // 로그인 Form Action Url
                .successHandler(new AuthenticationSuccessHandler() { // 로그인 성공 후 핸들러
                    @Override
                    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
                        System.out.println("authentication = " + authentication.getName());
                        response.sendRedirect("/");
                    }
                }) 
                .failureHandler(new AuthenticationFailureHandler() { // 로그인 실패 후 핸들러
                    @Override
                    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
                        System.out.println("exception = " + exception.getMessage());
                        response.sendRedirect("/login");
                    }
                })
                .permitAll(); 

        return http.build();
    }
}
  • 현재 코드의 인가 정책을 살펴보면 어떠한 요청에도 인증을 받도록 되어있기 때문에 로그인 페이지도 인증을 요구함

  • 로그인 페이지는 인증을 받지 않아도 접근 가능해야하므로 permitAll() 메소드를 사용함

  • 현재 /loginPage 경로로 이동하는 사용자는 인증을 받지 않아도 접근이 가능하게 설정

  • 인증 받지 않은 사용자의 경우 직접 설정한 로그인 페이지로 이동하게 함

  • 로그인 성공 및 실패 시 핸들러 동작

  • 로그인 페이지로 리다이렉트됨


참고 자료: 개발자가 될 사람

0개의 댓글