thymeleaf 에서 spring-security를 이용해 아이디, 권한 값을 비교해서 사용하기

오세훈·2023년 11월 11일
0

spring-boot

목록 보기
3/7

예시 코드

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

<!-- 로그인 하지 않은 경우 -->
<th:block sec:authorize="isAnonymous()">
    <li class="nav-item">
        <a th:href="@{/common/join}" class="nav-link">회원가입</a>
    </li>
    <li class="nav-item">
        <a th:href="@{/common/login}" class="nav-link">로그인</a>
    </li>
</th:block>
  

<!-- 로그인을 한 경우 -->
<th:block sec:authorize="isAuthenticated()">
    <li class="nav-item active">아이디: <span th:text="${#authentication.principal}"></span></li>
    <li class="nav-item active">직급: <span th:text="${#authentication.authorities}"></span></li>
    <li class="nav-item">
        <a th:href="@{/chat/chatList(id=${#authentication.principal})}" class="nav-link">채팅</a>
    </li>
    <li class="nav-item">
        <a th:href="@{/user/updateForm(name=${#authentication.principal})}" class="nav-link">수정하기</a>
    </li>
    <li class="nav-item">
        <form th:action="@{/logout}" method="post">
            <input type="hidden" th:name="${_csrf.parameterName}" th:value="${_csrf.token}" />
            <button type="submit" class="nav-link">로그아웃</button>
        </form>
    </li>
    <li class="nav-item">
        <a th:href="@{/user/withdraw(id=${#authentication.principal})}" class="nav-link">탈퇴하기</a>
    </li>
</th:block>
  

<!-- admin인 경우에 보여지도록 설정, spring el-->
<th:block sec:authorize="hasAuthority('ADMIN')">
    <li class="nav-item"><a th:href="@{/admin/admIndex}" class="nav-link">관리자 페이지</a></li>
</th:block>
  

<!-- emp인 경우에 보여지도록 설정, spring el -->
<th:block sec:authorize="hasAuthority('EMP')">
    <li class="nav-item"><a th:href="@{/emp/empIndex}" class="nav-link">직원 페이지</a></li>
</th:block>
  

<!-- user인 경우에 보여지도록 설정, spring el -->
<th:block sec:authorize="hasAuthority('USER')">
    <li class="nav-item"><a th:href="@{/user/userIndex}" class="nav-link">마이 페이지</a></li>
</th:block>
  

<!-- 권한과 아이디를 같이 비교하는 경우 -->
<th:block th:if="${#authentication.principal eq product.id or #authorization.expression('hasAuthority(''ADMIN'')')}">
	  <a th:href="@{/product/comUpdate(no=${product.no})}" class="btn btn-primary">수정</a>
	  <a th:href="@{/product/productDelete(no=${product.no})}" class="btn btn-danger">삭제</a>
</th:block>
profile
자바 풀 스택 주니어 개발자

0개의 댓글