본문 바로가기

Web/spring

[Spring Security] Handle Spring Security Exceptions

728x90

https://www.baeldung.com/spring-security-exceptions

 


Spring Security는 비즈니스 로직에 대한 호출을 제어하거나 특정 URL에 대한 HTTP 요청 액세스를 제한한다

해당 보안 계층에서 Exceptions 처리가 어떻게 진행되는지 알아보자

 

  • Authentication Success Handler
  • Authentication Failure Handler
  • Access Denied Handler

 

 


Security Configuration

 

This will be in charge of managing all the security configurations of the application

 

SecurityFilterChain

@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
    http.csrf()
        .disable()
        .httpBasic()
        .disable()
        .authorizeRequests()
        .antMatchers("/login")
        .permitAll()
        .antMatchers("/customError")
        .permitAll()
        .antMatchers("/access-denied")
        .permitAll()
        .antMatchers("/secured")
        .hasRole("ADMIN")
        .anyRequest()
        .authenticated()
        .and()
        .formLogin()
        .failureHandler(authenticationFailureHandler())
        .successHandler(authenticationSuccessHandler())
        .and()
        .exceptionHandling()
        .accessDeniedHandler(accessDeniedHandler())
        .and()
        .logout();
    return http.build();
}

 

 

여기서 antMatchers를 보면, such as “/login”, “/customError”, and “/access-denied” 와 같은 redirection URL에 access 할 때 제한하지않고 모두 접근 할 수 있도록 .permitAll() << 를 지정해두었다 권한이 어떻든 모두 들어올 수 있게 해준다는 의미이다.

 

만약 권한별로 해당 URL은 보여주고 싶지 않을 때는 "/secured"의 hasRole 부분을 사용하면 된다

 

 

 

define the types of exceptions that we can handle

 

@Bean
public AuthenticationFailureHandler authenticationFailureHandler() {
    return new CustomAuthenticationFailureHandler();
} 

@Bean
public AuthenticationSuccessHandler authenticationSuccessHandler() {
   return new CustomAuthenticationSuccessHandler();
}

@Bean
public AccessDeniedHandler accessDeniedHandler() {
   return new CustomAccessDeniedHandler();
}

 

AuthenticationSuccessHandler 를 보면 인증에 성공 했을 때의 처리 코드이다

 

 

실패 처리는 AuthenticationFailureHandler 의 해당 코드 내부에서 예외유형을 정의해주면 된다.

 

 

 

 

Authentication Failure Handler

사용자가 로그인에 실패할 때 발생하는 예외를 관리하는 역할을 담당한다

이 인터페이스는 처리기 논리를 사용자 지정하는 onAuthenticationFailure() 메서드를 제공하고 있다.

로그인 시도 실패 시 Spring Security에 의해 호출된다.

public class CustomAuthenticationFailureHandler implements AuthenticationFailureHandler {

    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) 
      throws IOException {
        response.sendRedirect("/customError");
    }
}

 

 

 

 

 

Access Denied Handler

이는 권한이 없는 사용자가 액세스 할 때 액세스 거부 예외를 발생시키는 코드이다.

기본 403 액세스 거부 페이지가 구현되어 있으나 커스텀도 가능하다.

AccessDeniedHandler 인터페이스 에 의해 관리된다.

또한 사용자를 403 페이지로 리디렉션하기 전에 논리를 사용자 지정하기 위한 handle() 메서드를 제공하고 있다.

 

public class CustomAccessDeniedHandler implements AccessDeniedHandler {

    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException exc) throws IOException {
        response.sendRedirect("/access-denied");
    }
}
728x90