[Spring Security]토이프로젝트를 위한 공부(3) - Thymeleaf에서 Principal 사용하기

gamja·2022년 11월 6일
0

강의를 막무가내로 따라 하는 건 의미가 없다고 생각하여 내가 추가 하고 싶은 기능이나 강의와는 조금 다르게 구현하고자 하는 부분은 배운 내용을 적용하면서 구현해보고 있다. 이번에는 Thymeleaf에서 Principal 객체를 사용하는 법을 알아보고자 한다.

Thymeleaf에서 Principal 사용

1. gradle에 설정 추가

implementation 'org.thymeleaf.extras:thymeleaf-extras-springsecurity5'

2. HTML에 선언

<html xmlns:th="http://www.thymeleaf.org"
      xmlns:sec="http://www.thymeleaf.org/extras/spring-security">

3. Thymeleaf 작성

아래와 같이 sec:authorize 를 통해서 권한이 존재하는지 여부를 확인할 수 있다.

  • sec:authentication="principal.authorities : 해당 유저가 가지고 있는 권한들을 불러올 수 있다.
    sec:authentication="name" : 해당 유저의 name을 가지고 온다.

4. 적용 결과

   <!--login, logout, signup 버튼-->
            <div class="col-4 d-flex justify-content-end align-items-center">
                <a class="link-secondary" href="#" aria-label="Search">
                  <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="2" class="mx-3" role="img" viewBox="0 0 24 24"><title>Search</title><circle cx="10.5" cy="10.5" r="7.5"/><path d="M21 21l-5.2-5.2"/></svg>
                </a>
                        <!-- 만약 로그인을 한 경우라면 logout만 나오도록 하고, 로그인을 하지 않았다면 login과 signup이 나오도록 한다.-->
                 
                <a class="btn btn-sm btn-outline-secondary m-1" sec:authorize="!isAuthenticated()" href="#" th:href="@{/account/login}">Login</a>  <!--권한 존재 여부-->
                <a class="btn btn-sm btn-outline-secondary m-1" sec:authorize="!isAuthenticated()" href="#" th:href="@{/account/register}">Sign up</a>
                <form class="form-inline my-2 my-lg-0" sec:authorize="isAuthenticated()">
                    <span class="text-white" sec:authentication="name">사용자</span>
                    <span class="text-white mx-2" sec:authentication="principal.authorities">권한</span>                            <!--모든 권한을 가져온다.-->   
                    <button class="btn btn-sm btn-outline-secondary m-1" type="submit">Logout</button>
                    
                </form>
              </div>  

🧩 Spring Security로 로그아웃하기

 <form class="form-inline my-2 my-lg-0" sec:authorize="isAuthenticated()" method="post" th:action="@{/logout}">
         <span class="text-white" sec:authentication="name">사용자</span>
         <span class="text-white mx-2" sec:authentication="principal.authorities">권한</span>                            
         <button class="btn btn-sm btn-outline-secondary m-1" type="submit">Logout</button>
 </form>

이렇게 해주면 Logout 버튼을 누를 시 바로 로그아웃이 됨!!
완전 편리하다.... Spring Security 체고

profile
눈도 1mm씩 쌓인다.

0개의 댓글