인증 절차 문제로 리다이랙트 된 후에 이전에 요청했던 정보를 담고 있는 savedRequest 객체를 쿠키 혹은 세션에 저장, 필요시 다시 가져와 시행
HttpSessionRequestCache → Session에 request를 저장
client → 인증 받지 않은 상태로 접근 → HttpSessionRequestCache → savedRequest → HttpSession (DefaultSavedRequest) / 인증 이전의 요청 정보를 저장 → redirect(/login)
client → 인증 시도 → AuthenticationSuccessHandler → redirect(/user)
client → 인증 시도 → AuthenticationSuccessHandler -getRedirectUrl()→ 이전에 가고자 했던 경로 → HttpSession (DefaultSavedRequest) {HttpSessionRequestCache → HttpSession (DefaultSavedRequest)}
//어떤 경로로 이동할지 명시하지 않아도 cache 로 부터 저장한 request 객체를 가져와서 redirect할 url을 추출 → 이동
HttpSessionRequestCache requestCache = new HttpSessionRequestCache();
requestCache.setMatchingRequestParameterName("customParam=y");
http
.requestCache((cache) -> cache
.requestCache(requestCache)
);
요청을 저장하지 않도록 하려면 NullRequestCache 구현 사용
RequestCache nullRequestCache = new NullRequestCache(); http
.requestCache((cache) -> cache .requestCache(nullRequestCache)
);
RequestCacheAwareFilter는 이전에 저장했던 웹 요청을 다시 불러오는 역할
savedRequest가 현재 Request와 일치하면, 요청을 필터체인의 doFilter 메소드에 전달, SavedRequest가 없으면 필터는 원래 Request 진행
client → RequestCacheAwareFilter → SavedRequest !=null (SavedRequest가 쿠키 혹은 세션에 존재하는지 확인) -N→ chain.doFilter
client → RequestCacheAwareFilter → SavedRequest !=null (SavedRequest가 쿠키 혹은 세션에 존재하는지 확인) -Y→ SavedRequest == currentRequest (SavedRequest가 현재 Request와 일치하는지 확인)
-N→ chain.doFilter(request,response)
-Y→ chain.doFilter(SavedRequest ,response)
@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
HttpSessionRequestCache requestCache = new HttpSessionRequestCache();
http
.authorizeHttpRequests(auth -> auth
.requestMatchers("/logoutSuccess").permitAll()
.anyRequest().authenticated())
.formLogin(form -> form
.successHandler(new AuthenticationSuccessHandler() {
@Override
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
SavedRequest savedRequest = requestCache.getRequest(request, response); //SavedRequest를 가져오고
String redirectUrl = savedRequest.getRedirectUrl(); //여러 값을 가져올 수 있다.
response.sendRedirect(redirectUrl);
}
})
);
return http.build(); // securityFilterChain 생성된다.
}