Ex) 인증이 필요한 페이지를 요청했다가 로그인 페이지로 리다이렉트 되었을 경우에 로그인 성공 시 다시 원래 요청한 페이지로 이동할 수 있도록 함.@Configuration
@EnableWebSecurity
public class SecurityConfig {
@Bean
public SecurityFilterChain filterChain(HttpSecurity httpSecurity) throws Exception {
....
httpSecurity.requestCache((cache) -> cache.disable());
....
return httpSecurity.build();
}
}
핵심 로직
@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);
}
}
