로그 아웃 요청은 POST 요청과 GET 요청으로 받는다.
- POST : form태그
- GET : a태그 - SecurityContextLogoutHandler 사용
인증여부에 따른 SpringSecurity Tag 사용법
- <li sec:authorize="isAnonymous()"> <a>로그인</a></li>
- <li sec:authorize="isAuthenticated()"><a>로그아웃</a></li>
ThymeLeaf 기준.
등록할 의존 : thymeleaf-extras-springsecurity5
<dependency>
<groupId>org.thymeleaf.extras</groupId>
<artifactId>thymeleaf-extras-springsecurity5</artifactId>
</dependency>
정의할 xmlns : www.thymeleaf.org/thymeleaf-extras-springsecurity5
<html lang="ko" xmlns:th="http://www.thymeleaf.org"
xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity5">
접두사인 sec 를 이용, authorize="" < isAnonymous() , isAuthenticated() 로 인증여부 판단
<li class="nav-item" sec:authorize="isAnonymous()"><a class="nav-link text-light" th:href="@{/login}">로그인</a></li>
<li class="nav-item" sec:authorize="isAnonymous()"><a class="nav-link text-light" th:href="@{/users}">회원가입</a></li>
<li class="nav-item" sec:authorize="isAuthenticated()"><a class="nav-link text-light" th:href="@{/logout}">로그아웃</a></li>
LogoutController 설정
깊게 봐야 할 점은 Authentication 객체를 SecurityContextHolder에서 SecurityContext를 꺼내서 가져온다는 점
Authentication 객체가 null 이 아니라면 (있다면) SecurityContextLogoutHandler 객체를 생성하여 .logout() 메서드를 이용해 Session 과 Authencation 을 null로 만드는 점
@GetMapping("/logout")
public String logout(HttpServletRequest request, HttpServletResponse response){
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();// SecurityContextHolder 에서 Authentication 객체 추출
if(authentication != null){
new SecurityContextLogoutHandler().logout(request, response, authentication);//Authentication 객체 존재시 SecurityContextLogoutHandler 가 session 과 authentication 객체 삭제
}
return "redirect:/";
}
'springframework > 시작하자SpringSecurity' 카테고리의 다른 글
31.CustomAuthenticationSuccessHandler (0) | 2020.09.29 |
---|---|
30.WebAuthenticationDetails, AuthenticationDetailsSource (0) | 2020.09.29 |
28.CustonLoginPage (0) | 2020.09.28 |
27.인증구현, CustomAuthenticationProvider (0) | 2020.09.27 |
26.인증 프로세스 구현, CutonUserDetailsService (0) | 2020.09.27 |