Spring Security - 16. RequestCacheAwareFilter

하쮸·2025년 2월 26일

1. RequestCacheAwareFilter.

  • Spring Security - architecture(RequestCache)
  • RequestCacheAwareFilter는 스프링 시큐리티 의존성을 추가하면 자동으로 등록되는 시큐리티 필터체인에 소속되어 있는 필터 중 하나임.
    해당 필터의 목적은 저장된 요청이 캐시되어 있고 현재 요청과 일치하는 경우 저장된 요청을 재구성하는 일을 담당함.
    • 즉 사용자가 로그인 등의 이유로 리다이렉트 되었을 때, 로그인 후에도 이전 요청을 기억하고 다시 처리하도록 도와줌.
      Ex) 인증이 필요한 페이지를 요청했다가 로그인 페이지로 리다이렉트 되었을 경우에 로그인 성공 시 다시 원래 요청한 페이지로 이동할 수 있도록 함.
  • 사용자가 직접 커스텀 시큐리티필터체인을 등록하더라도 기본적으로 등록되기 때문에 아래와 같은 코드를 통해서 비활성화 시킬 수 있음.
@Configuration
@EnableWebSecurity
public class SecurityConfig {
    @Bean
    public SecurityFilterChain filterChain(HttpSecurity httpSecurity) throws Exception {
    
    			....
                
                
        httpSecurity.requestCache((cache) -> cache.disable());

				....

        return httpSecurity.build();
    }
}

1-1. 상세 코드.

핵심 로직

	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
			throws IOException, ServletException {
        // 이전에 저장된 요청이 현재 요청과 일치하는지 확인.
        // 만약 저장된 요청이 있다면, 해당 요청을 반환하고, 없다면 null을 반환.
		HttpServletRequest wrappedSavedRequest = this.requestCache.getMatchingRequest((HttpServletRequest) request,
				(HttpServletResponse) response);
        // chain.doFilter()는 다음 필터로 요청을 전달하는 역할.
		// 만약 저장된 요청(wrappedSavedRequest)이 존재한다면 해당 요청을 전달.
		// 저장된 요청이 없다면 원래 요청(request)을 전달하여 요청을 처리.
		chain.doFilter((wrappedSavedRequest != null) ? wrappedSavedRequest : request, response);
	}
package org.springframework.security.web.savedrequest;

import java.io.IOException;

import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.ServletRequest;
import jakarta.servlet.ServletResponse;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import org.springframework.util.Assert;
import org.springframework.web.filter.GenericFilterBean;

/**
 * Responsible for reconstituting the saved request if one is cached and it matches the
 * current request.
 * <p>
 * It will call
 * {@link RequestCache#getMatchingRequest(HttpServletRequest, HttpServletResponse)
 * getMatchingRequest} on the configured <tt>RequestCache</tt>. If the method returns a
 * value (a wrapper of the saved request), it will pass this to the filter chain's
 * <tt>doFilter</tt> method. If null is returned by the cache, the original request is
 * used and the filter has no effect.
 *
 * @author Luke Taylor
 * @since 3.0
 */
public class RequestCacheAwareFilter extends GenericFilterBean {

	private RequestCache requestCache;

	public RequestCacheAwareFilter() {
		this(new HttpSessionRequestCache());
	}

	public RequestCacheAwareFilter(RequestCache requestCache) {
		Assert.notNull(requestCache, "requestCache cannot be null");
		this.requestCache = requestCache;
	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
			throws IOException, ServletException {
		HttpServletRequest wrappedSavedRequest = this.requestCache.getMatchingRequest((HttpServletRequest) request,
				(HttpServletResponse) response);
		chain.doFilter((wrappedSavedRequest != null) ? wrappedSavedRequest : request, response);
	}

}

2. ExceptionTranslationFilter

  • Spring Security - architecture(Handling Security Exceptions)
  • ExceptionTranslationFilter는 스프링 시큐리티에서 발생하는 AccessDeniedException과 AuthenticationException 예외를 처리하는 역할을 함.
    • AuthenticationException, AccessDeniedException를 HTTP 응답으로 변환하여 사용자에게 적절한 응답을 제공함.
    • ExceptionTranslationFilter는 Security Filter 중 하나로 FilterChainProxy에 삽입됨.
  • 인증 실패 처리 (AuthenticationException).
    • 인증이 필요한 페이지에 로그인하지 않은 상태로 접근하면 authenticationEntryPoint를 실행하여 로그인 페이지로 이동하도록 함.
      이를 통해, 스프링 시큐리티에서 인증 실패 시 일관된 방식으로 처리할 수 있음.
  • 접근 거부 처리 (AccessDeniedException).
    • 접근 권한이 없는 사용자가 리소스에 접근하면 필터가 사용자의 인증 상태를 확인.
      • 로그인하지 않은 사용자(익명 사용자).
        • 로그인 페이지로 이동 (authenticationEntryPoint 실행).
      • 로그인한 사용자.
        • 접근 거부 (AccessDeniedHandler 실행).
    • 기본적으로 AccessDeniedHandlerImpl이 사용.
  • ExceptionTranslationFilter는 AuthenticationException 또는 AccessDeniedException를 감지하여, 로그인 페이지로 유도하거나 403에러를 반환하는 역할.
profile
Every cloud has a silver lining.

0개의 댓글