1. 개요

스프링 시큐리티로 로그인을 구현했으니, 스프링 시큐리티로 로그아웃도 구현해보자. 로그아웃은 SecurityConfig 같은 시큐리티 config 클래스에서 설정해주면 된다.

 

스펙

  • Spring Security
  • JWT

 

2. SecurityConfig 코드

@Configuration
@EnableWebSecurity
@RequiredArgsConstructor
public class SecurityConfig {

    private final JwtTokenProvider jwtTokenProvider;
    
    ...

    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        ....
        http.
            ....
            .logout(logout -> logout
                                .logoutUrl("/logout")
                                .logoutSuccessUrl("/index")
                                // 로그아웃 핸들러 추가 (세션 무효화 처리)
                                .addLogoutHandler((request, response, authentication) -> {
                                    HttpSession session = request.getSession();
                                    session.invalidate();
                                })
                                // 로그아웃 성공 핸들러 추가 (리다이렉션 처리)
                                .logoutSuccessHandler((request, response, authentication) ->
                                        response.sendRedirect("/index"))
                                .deleteCookies("JSESSIONID", "access_token"));

        return http.build();
    }
}

 

3. 코드 톺아보기 - 로그아웃

SecurityConfig 클래스의 filterChain() 내부에서 logout을 설정해주면 되는데, 구체적인 과정은 다음과 같다.

 

  • .logoutUrl() : 로그아웃을 요청할 url 설정
  • .logoutSuccessUrl() : 로그아웃 성공시 리다이렉트 할 url
  • .addLogoutHandler() : 세션 무효화 처리를 할 로그아웃 핸들러
    • 로그아웃 성공 실패 여부 상관없이 시도했을 때 수행된다
  • .logoutSuccessHandler() : 로그아웃 성공 핸들러
    • addLogoutHandler가 수행되고, 로그아웃이 성공했을 때 수행된다
  • .deleteCookies() : 쿠키 값 삭제 
    • "JSESSIONID" 를 설정해야 쿠키 에러가 발생하지 않는다.
    • jwt 토큰을 쿠키에 "access_token=~" 형태로 저장했으므로 "access_token"도 삭제한다.
.logout(logout -> logout
        .logoutUrl("/logout")
        .logoutSuccessUrl("/index")
        // 로그아웃 핸들러 추가 (세션 무효화 처리)
        .addLogoutHandler((request, response, authentication) -> {
            HttpSession session = request.getSession();
            session.invalidate();
        })
        // 로그아웃 성공 핸들러 추가 (리다이렉션 처리)
        .logoutSuccessHandler((request, response, authentication) ->
                response.sendRedirect("/index"))
        .deleteCookies("JSESSIONID", "access_token"));

 

SecurityContextLogoutHandler

코드 상에서 직접 세션을 무효화하거나 쿠키를 삭제하지 않더라도 세션을 무효화하고, 쿠키를 삭제하는 기능을 한다. 

순서는 개발자가 직접 정의한 핸들러 -> 스프링 시큐리티 제공 핸들러 로 진행된다.

 

참고

https://goto-pangyo.tistory.com/170

'Spring > SpringSecurity' 카테고리의 다른 글

[Spring Security] Spring Security, JWT 토큰 로그인  (0) 2024.05.18

+ Recent posts