[ODOP] 72일차 - Spring security Logout 프로세스

[ODOP] 72일차 - Spring security Logout 프로세스
💡
최신 버전에서는 아래의 방식과는 조금 다르게 권한설정을 진행한다.
아래의 설명들은 모두 구버전(2.6.7)을 기준으로 설명하고 있다
  1. request (/logout)
    사용자가 로그아웃을 요청한다.
  2. 세션 무효화, 인증토큰 삭제, 쿠키정보 삭제, 로그인 페이지로 리다이렉트

설정

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .authorizeRequests()
            .anyRequest()
						.authenticated();

        logoutConfigure(http);
    }

    private void logoutConfigure(HttpSecurity http) throws Exception {
        http.logout()                                       // 로그아웃 기능이 동작
            .logoutUrl("/logout")                           // 로그아웃 처리 URL
            .logoutSuccessUrl("/login")                     // 로그아웃 성공 후 이동 페이지
            .deleteCookies("JSESSIONID", "remember-me")     // 로그아웃 후 쿠키 삭제
            .addLogoutHandler(logoutHandler())              // 로그아웃 핸들러
            .logoutSuccessHandler(logoutSuccessHandler());  // 로그아웃 성공 후 핸들러
    }
    private LogoutSuccessHandler logoutSuccessHandler() { return null; }
    private LogoutHandler logoutHandler() { return null; }
}
  • 로그아웃 로직을 작동시키게 되면 세션, 인증 토큰 정보는 기본적으로 삭제 된다.
  • 로그아웃 이후의 동작을 진행하고 싶다면 위 설정에서의 핸들러를 구현해주고 등록해주면 된다.
  • deleteCookies
    Security 에서는 remember-me 라는 이름의 쿠키를 사용해 로그인에 대한 처리를 진행 한다. 따라서 해당 쿠키 내용을 지워주는 동작을 명시 해 둬야 함.

로그아웃 필터 프로세스

  1. 사용자의 요청이 들어온다. (기본적으로는 POST)
  2. LogoutFilter 가 이를 감지한다.
  3. AntPathRequestMatcher 가 지정된 경로 (/logout) 로 요청이 들어왔는지 확인하고, 만약 아니라면 다음 필터체인이 동작하게 함(이 때 로그아웃 프로세스는 중지)
  4. SecurityContext 에 있는 Authentication 을 꺼내와서 SecurityContextLogoutHandler 에게 넘겨준다.
  5. SecurityContextLogoutHandler 는 이를 수신하여 세션 무효화, 쿠키 삭제를 진행하고 SecurityContext 에 존재하던 해당 유저의 Authentication 정보를 null 로 초기화 한다.
  6. 실행의 흐름은 다시 LogoutFilter 로 넘어간다.
  7. 다른 흐름이 끝난 LogoutFilter 는 이제 SimpleUrlLogoutSuccessHandler 에게 그 흐름을 넘긴다.
  8. SpringSecurity 에서 기본적으로 제공하는 로그인 페이지를 사용자에게 노출시킨다.
💡
만약 GET 방식으로 로그아웃 처리를 하고 싶다면 SecurityContextLogoutHandler 를 활용하여 할 수 있다.