스터디-Spring

[스프링 시큐리티] ExceptionTranslationFilter

일태우 2022. 1. 17. 22:20

필터 체인에서 발생하는 AccessDeniedException과 AuthenticationException을 처리하는 필터

private void handleAccessDeniedException(HttpServletRequest request, HttpServletResponse response,
FilterChain chain, AccessDeniedException exception) throws ServletException, IOException {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
boolean isAnonymous = this.authenticationTrustResolver.isAnonymous(authentication);
if (isAnonymous || this.authenticationTrustResolver.isRememberMe(authentication)) {
if (logger.isTraceEnabled()) {
logger.trace(LogMessage.format("Sending %s to authentication entry point since access is denied",
authentication), exception);
}
sendStartAuthentication(request, response, chain,
new InsufficientAuthenticationException(
this.messages.getMessage("ExceptionTranslationFilter.insufficientAuthentication",
"Full authentication is required to access this resource")));
}
else {
if (logger.isTraceEnabled()) {
logger.trace(
LogMessage.format("Sending %s to access denied handler since access is denied", authentication),
exception);
}
this.accessDeniedHandler.handle(request, response, exception);
}
}
  • 익명이면 startAuthentication 진행
  • 아니면 accessDeniedHandler를 통해 exception 처리

 

주의할점 UsernamePasswordAuthenticationFilter의 AuthenticationException은 상위 클래스인 AbstractAuthenticationProcessingFilter에서 처리한다.

 

AbstractAuthenticationProcessingFilter -> AuthenticationFailureHandler(SimpleUrlAuthenticationFailureHandler).onAuthenticationFailure -> saveException

protected final void saveException(HttpServletRequest request, AuthenticationException exception) {
if (this.forwardToDestination) {
request.setAttribute(WebAttributes.AUTHENTICATION_EXCEPTION, exception);
return;
}
HttpSession session = request.getSession(false);
if (session != null || this.allowSessionCreation) {
request.getSession().setAttribute(WebAttributes.AUTHENTICATION_EXCEPTION, exception);
}
}

session에 exception을 담는 역할