[Spring Security] Logout 구현하기

2024. 1. 4. 13:46백엔드/Spring Boot

이번에는 로그아웃을 구현하는 코드에 대하여 작성해보려고 한다. 

 

 

# Logout 프로세스 

  1. 클라이언트가 서버로 로그아웃 요청을 보낸다. 
  2. 서버가 세션 무효화, 인증토큰 삭제, 쿠키 정보 삭제 처리 후 로그인 페이지로 리다이렉트 시킨다. 

 

 

# Logout  API에 대하여 알아보자

  • logoutUrl() : 로그아웃 처리 경로 
  • logoutSuccessUrl() : 로그아웃 성공 후 이동시킬 페이지 경로 
  • addLogoutHandler : 로그아웃 핸들러, 로그아웃 성공 여부와 상관없이 실행 
  • logoutSuccessHandler : 로그아웃 성공 핸들러
  • deleteCookies() : 로그아웃 후 지정한 이름의 쿠키를 삭제한다. 
@Configuration
@EnableWebSecurity
public class SecurityConfig {
    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        // 로그인 인증 ~ 로그인 코드 생략...

        // 로그아웃
        http.logout(
                logout -> logout
                        .logoutUrl("/logout") // 로그아웃 처리 URL
                        .logoutSuccessUrl("/login") // 로그아웃 성공 후 이동시킬 페이지
                        // 로그아웃 핸들러, 로그아웃 성공 여부와 상관없이 실행된다.
                        .addLogoutHandler(new LogoutHandler() {
                            @Override
                            public void logout(HttpServletRequest request, HttpServletResponse response, Authentication authentication) {
                                HttpSession httpSession = request.getSession();
                                httpSession.invalidate();
                            }
                        })
                        // 로그아웃 성공 핸들러
                        .logoutSuccessHandler(new LogoutSuccessHandler() {
                            @Override
                            public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
                                System.out.println("로그아웃 성공");
                                response.sendRedirect("/login");
                            }
                        })
                        .deleteCookies("remember-me") // 로그아웃 후 쿠키 삭제

        );
        return http.build();
    }

}

 

 

 

 

 

 

 

Reference

인프런 '스프링 시큐리티 - Spring Boot 기반으로 개발하는 Spring Security' - 정수원

 

스프링 시큐리티 강의 - 인프런

초급에서 중.고급에 이르기까지 스프링 시큐리티의 기본 개념부터 API 사용법과 내부 아키텍처를 학습하게 되고 이를 바탕으로 실전 프로젝트를 완성해 나감으로써 스프링 시큐리티의 인증과

www.inflearn.com