스터디-Spring

[스프링 시큐리티] ExceptionTranslationFilter - 예외 처리 필터

일태우 2022. 2. 15. 09:53

https://docs.spring.io/spring-security/site/docs/5.1.5.RELEASE/reference/htmlsingle/#exceptiontranslationfilter

 

Spring Security Reference

The authenticator is also responsible for retrieving any required user attributes. This is because the permissions on the attributes may depend on the type of authentication being used. For example, if binding as the user, it may be necessary to read them

docs.spring.io

 ExceptionTranslationFilter는 모든 Spring Security 예외를 감지하고 처리하는 필터

 

예외는 일반적으로 AbstractSecurityInterceptor에서 발생하는데 이는 바로뒤에 있는 필터인 FilterSecurityInterceptor가 구현체있다.

 

내부 구조를 보면 try catch로 이후 필터의 동작을 감싸고 있음

private void doFilter(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
      throws IOException, ServletException {
   try {
      chain.doFilter(request, response);
   }
   catch (IOException ex) {
      throw ex;
   }
   catch (Exception ex) {
      // Try to extract a SpringSecurityException from the stacktrace
      Throwable[] causeChain = this.throwableAnalyzer.determineCauseChain(ex);
      RuntimeException securityException = (AuthenticationException) this.throwableAnalyzer
            .getFirstThrowableOfType(AuthenticationException.class, causeChain);
      if (securityException == null) {
         securityException = (AccessDeniedException) this.throwableAnalyzer
               .getFirstThrowableOfType(AccessDeniedException.class, causeChain);
      }
      if (securityException == null) {
         rethrow(ex);
      }
      if (response.isCommitted()) {
         throw new ServletException("Unable to handle the Spring Security Exception "
               + "because the response is already committed.", ex);
      }
      handleSpringSecurityException(request, response, chain, securityException);
   }
}
  • AuthenticationException -> AuthenticationEntryPoint
    • 인증이 안되어 있을 경우 발생
    • sendStartAuthentication 실행(인증 유도)
protected void sendStartAuthentication(HttpServletRequest request, HttpServletResponse response, FilterChain chain,
      AuthenticationException reason) throws ServletException, IOException {
   // SEC-112: Clear the SecurityContextHolder's Authentication, as the
   // existing Authentication is no longer considered valid
   SecurityContextHolder.getContext().setAuthentication(null);
   this.requestCache.saveRequest(request, response);
   this.authenticationEntryPoint.commence(request, response, reason);
}
  • AccessDeniedException -> AccessDeniedHandler
    • 인가가 되지 않은 경우 발생
    • AccessDeniedHandler가 처리하는데 기본적으로 403에러를 보여줌