Thymeleaf

[Thymeleaf] 타임리프로 화면단에서 사용자 시큐리티 정보 가져오기

cornarong 2021. 11. 10. 23:01

스프링 시큐리티 인증을 받은 로그인 한 사용자의 정보를 타임리프에서 사용하고 싶을 때 사용합니다.

 

.gradle 설정

implementation 'org.springframework.boot:spring-boot-starter-security'
// 타임리프에서 스프링시큐리티의 문법이나 형식을 지원하는 확장팩 라이브러리
implementation 'org.thymeleaf.extras:thymeleaf-extras-springsecurity5'

 

우선 네임스페이스를 등록합니다.

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

 

사용 예시

<p th:text="${#authentication.name}"></p>
<p th:text="${#authentication.authorities}"></p>
<p th:text="${#authentication.authenticated}"></p>

 

출력 결과

1. 사용자 이름

2. 사용자 권한

3. 사용자 인증여부

 

추가로 아래는 조건의 결과를 true,  false로 if와 같은 기능으로 사용 가능합니다.

<div sec:authorize="isAuthenticated()"></div>
<div sec:authorize="hasRole('ROLE_ADMIN')"></div>
<div sec:authorize="hasRole('ROLE_USER')"></div>

 

참조.

 

Thymeleaf + Spring Security integration basics - Thymeleaf

Have you switched to Thymeleaf but your login and error pages are still using JSP? In this article we will see how to configure your Spring application to use Thymeleaf for login and error pages. All the code seen here comes from a working application. You

www.thymeleaf.org