RequestCache

황상익·2024년 9월 9일

security

목록 보기
5/16
  • RequestCache

인증 절차 문제로 리다이랙트 된 후에 이전에 요청했던 정보를 담고 있는 savedRequest 객체를 쿠키 혹은 세션에 저장, 필요시 다시 가져와 시행
HttpSessionRequestCache → Session에 request를 저장

  • SavedRequest
    SavedRequest은 로그인과 같은 인증 절차 후 사용자를 인증 이전의 원래 페이지로 안내하여 이전 요청과 관련된 정보를 저장
    여러 API들 제공

client → 인증 받지 않은 상태로 접근 → HttpSessionRequestCache → savedRequest → HttpSession (DefaultSavedRequest) / 인증 이전의 요청 정보를 저장 → redirect(/login)

client → 인증 시도 → AuthenticationSuccessHandler → redirect(/user)
client → 인증 시도 → AuthenticationSuccessHandler -getRedirectUrl()→ 이전에 가고자 했던 경로 → HttpSession (DefaultSavedRequest) {HttpSessionRequestCache → HttpSession (DefaultSavedRequest)}

//어떤 경로로 이동할지 명시하지 않아도 cache 로 부터 저장한 request 객체를 가져와서 redirect할 url을 추출 → 이동

  • requestCache API
    요청 Url에 customParam=y 이름의 매개 변수가 있는 경우 HttpSession에 저장된 SavedRequest을 꺼내오도록 설정 가능 (기본값은 “continue”)
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

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 생성된다.
    }
profile
개발자를 향해 가는 중입니다~! 항상 겸손

0개의 댓글