SpringBoot/Spring Security
ExceptionTranslationFilter
by BAYABA
2021. 9. 22.
- 개인 공부 목적으로 작성한 글입니다.
- 아래 출처를 참고하여 작성하였습니다.
1. ExceptionTranslationFilter ?
- Spring Security에서 인증/인가 예외 처리 필터입니다.
- ExceptionTranslationFilter는 SecurityInterceptor와 밀접한 관계가 있습니다.
- ExceptionTranslationFilter가 try-catch 블록으로 감싼 뒤 SecurityInterceptor를 실행하는 구조.
- 즉, SecurityInterceptor가 인증/인가 처리를 하는 과정에서 발생하는 예외를 처리합니다.
public class ExceptionTranslationFilter extends GenericFilterBean {
private AccessDeniedHandler accessDeniedHandler = new AccessDeniedHandlerImpl();
private AuthenticationEntryPoint authenticationEntryPoint;
private AuthenticationTrustResolver authenticationTrustResolver = new AuthenticationTrustResolverImpl();
private ThrowableAnalyzer throwableAnalyzer = new DefaultThrowableAnalyzer();
private RequestCache requestCache = new HttpSessionRequestCache();
// in ExceptionTranslationFilter.java
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) req;
HttpServletResponse response = (HttpServletResponse) res;
try {
chain.doFilter(request, response);
logger.debug("Chain processed normally");
}
catch (IOException ex) {
throw ex;
}
catch (Exception ex) {
// Try to extract a SpringSecurityException from the stacktrace
Throwable[] causeChain = throwableAnalyzer.determineCauseChain(ex);
RuntimeException ase = (AuthenticationException) throwableAnalyzer
.getFirstThrowableOfType(AuthenticationException.class, causeChain);
if (ase == null) {
ase = (AccessDeniedException) throwableAnalyzer.getFirstThrowableOfType(
AccessDeniedException.class, causeChain);
}
if (ase != null) {
handleSpringSecurityException(request, response, chain, ase);
}
else {
// Rethrow ServletExceptions and RuntimeExceptions as-is
if (ex instanceof ServletException) {
throw (ServletException) ex;
}
else if (ex instanceof RuntimeException) {
throw (RuntimeException) ex;
}
// Wrap other Exceptions. This shouldn't actually happen
// as we've already covered all the possibilities for doFilter
throw new RuntimeException(ex);
}
}
}
출처
- Spring Security - ExceptionTranslationFilter
- Class ExceptionTranslationFilter