Spring/시큐리티 기본원리

시큐리티 기본 원리( 22 ) - ExceptionTranslationFilter

_Jin_ 2025. 1. 29.

ExceptionTranslationFilter 목적

해당 필터는 DefaultSecurityFilterChain에 기본적으로 등록되는 필터로 열다섯 번째에 위치한다.

 

ExceptionTranslationFilter는 인증, 인가 과정에서 발생하는 예외를 핸들링하기 위한 동작을 수행한다.  

이러한 동작 수행에 있어서는 아래와 같은 흐름을 따른다. 

 

주요 로직

ExceptionTranslationFilter 클래스

public class ExceptionTranslationFilter extends GenericFilterBean implements MessageSourceAware {

}

 

doFilter

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);
	}
}

doFilter의 메소드 내부에서 예외를 catch하여 handleSpringSecurityException 메소드를 호출하며, 

예외를 담은 securityException을 파라미터로 넘겨준다.

 

handleSpringSecurityException 

흐름에 따라 인증/ 인가에 대한 핸들링의 시작점은 handleSpringSecurityException 메소드라고 볼 수 있으며,

내부 로직에서 각각 인증 / 인가에 대한 별도의 예외를 처리한다.

private void handleSpringSecurityException(HttpServletRequest request, HttpServletResponse response,
		FilterChain chain, RuntimeException exception) throws IOException, ServletException {
        // 인증에 대한 예외
	if (exception instanceof AuthenticationException) {
		handleAuthenticationException(request, response, chain, (AuthenticationException) exception);
	}
    	// 인가에 대한 예외
	else if (exception instanceof AccessDeniedException) {
		handleAccessDeniedException(request, response, chain, (AccessDeniedException) exception);
	}
}

 

전체 흐름 정리

인증과 인가에 대한 예외 처리를 담당하는 필터로 ExceptionTranslationFilter 가 있으며 전체 흐름에 대한 정리를 해보겠다.

 

인증 예외

인증과 관련한 예외가 발생한 경우, AuthenticationException이 발생한다.

이후 AuthenticationEntryPoint 호출하고 보통 로그인 페이지로 이동하게 만들며, 401에러를 발생시킨다. 

 

그와 동시에 ReqeustCache ( 기억이 안난다면, 앞의 RequestCacheAwareFilter 부분을 다시보자 ) 에 사용자가 본래 접근하려고 했던 경로를 기억한다. 

 

최종적으로 사용자가 인증에 성공하면, ReqeustCache 에 저장된 내용을 바탕으로 본래 수행하고자 했던 흐름을 따른다. 

 

인가 예외 

한편, 인가와 관련한 예외가 발생한 경우  AccessDeniedException가 발생하며, 

AccessDeniedHandler에서 예외를 처리하도록 호출

 

댓글