반응형
05-03 07:00
Today
Total
«   2024/05   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
관리 메뉴

개발하는 고라니

[Spring Boot] Security 사용자 정보 출력 in Thymeleaf 본문

Framework/Spring Boot

[Spring Boot] Security 사용자 정보 출력 in Thymeleaf

조용한고라니 2021. 3. 5. 17:24
반응형

Spring Security를 적용하여 사용자를 등록해 로그인에 성공했다면, thymeleaf에서 사용자의 정보를 출력할 수 있다. 'th:'를 쓸 것 같지만, Thymeleaf 공식 docs를 보면 예상과 다르게 JSP에서 쓰던 taglib를 사용한다. Spring Security를 JSP와 함께 써본 사람은 알겠지만 'sec:authentication="" '와 같은 것을 사용했었다.

 

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

그럼 간단하게 사용자의 정보를 출력하는 법을 알아보자.

 

우선 Thymeleaf에서 Spring Security를 이용하고자 한다면 반드시 필요햔 라이브러리가 있다. 필자는 Gradle을 사용하여하였다.

사용자의 정보를 추출할 경우 'Authentication'이라는 타입의 객체를 이용한다. 만약 사용자의 정보를 담고있는 객체가 MemberDTO라면 Authentication = MemberDTO 가 된다. 

implementation 'org.thymeleaf.extras:thymeleaf-extras-springsecurity5'
        <!--ROLE_USER 권한을 갖는다면 이 글이 보임-->
        <h1 sec:authorize="hasRole('ADMIN')">Has admin Role</h1>
        
        <!--ROLE_ADMIN 권한을 갖는다면 이 글이 보임-->
        <h1 sec:authorize="hasRole('USER')">Has user Role</h1> 

        <!--어떤 권한이건 상관없이 인증이 되었다면 이 글이 보임-->
        <div sec:authorize="isAuthenticated()">
            Only Authenticated user can see this Text
        </div>

        <!--인증시 사용된 객체에 대한 정보-->
        <b>Authenticated DTO:</b>
        <div sec:authentication="principal"></div>

        <!--인증시 사용된 객체의 Username (ID)-->
        <b>Authenticated username:</b>
        <div sec:authentication="name"></div>

        <!--객체의 권한-->
        <b>Authenticated user role:</b>
        <div sec:authentication="principal.authorities"></div>

'gorany1'이라는 ID로 로그인을 했고, ADMIN이라는 권한을 갖기에 위와 같이 출력되었다. 스프링 시큐리티에서는 username이 사용자의 이름이 아닌 사용자의 ID를 나타냄에 항상 유의하자.


이번엔 Controller에서 Model에 인증에 사용된 객체를 Model에 담아 보내는 방법이 있다.

@AuthenticationPrincipal 어노테이션은 별도의 캐스팅 작업 없이 직접 실제 MemberDTO 타입을 사용할 수 있기 때문에 좀 더 편하게 사용할 수 있게 한다.

    @GetMapping(value = "/sample")
    public void sample(@AuthenticationPrincipal MemberDTO memberDTO, Model model){

        log.info("Sample....");
        log.info(memberDTO);

        model.addAttribute("member", memberDTO);
    }
<div th:text="${member}"></div>

반응형

'Framework > Spring Boot' 카테고리의 다른 글

[Spring Boot] XSS  (0) 2021.03.28
[Spring Boot] Security 로그인 커스터마이징  (0) 2021.03.13
[Spring Boot] JPA 관련 용어  (0) 2021.02.20
[Spring Boot] @MappedSuperClass  (0) 2021.01.14
[Spring Boot] JPA 동적 검색 (QueryDsl)  (1) 2021.01.13
Comments