Search code examples
springspring-bootthymeleaf

Thymeleaf Spring Security - Store authentication into local variable


I am using Thymeleaf Spring Security in my Spring Boot project.

In the html file, I have multiple times in a row a couple of checks to display text based on user role (Admin, user, not logged in).

<div class="container">
    <div sec:authorize="hasAuthority('ADMIN')">Admin text 1</div>
    <div sec:authorize="hasAuthority('USER')">User text 1</div>
    <div sec:authorize="hasAuthority('ANONYMOUS')">Not logged in text 1</div>
    ....
    <div sec:authorize="hasAuthority('ADMIN')">Admin text 2</div>
    <div sec:authorize="hasAuthority('USER')">User text 2</div>
    <div sec:authorize="hasAuthority('ANONYMOUS')">Not logged in text 2</div>
    ....
</div>

I know you can use a local variables with Thymeleaf. I would like to save the authority checks into local variables so I can write more efficient code afterwards. Example below, but the local variable part is obviously incorrect.

<div class="container" th:with="isAdmin=${hasAuthority('ADMIN')},isUser=${hasAuthority('USER')}">
    <div th:text="${isAdmin} ? "Admin text 1" : ${isUser} ? "User text 1" : "Not logged in text 1"></div>
    ....
    <div th:text="${isAdmin} ? "Admin text 2" : ${isUser} ? "User text 2" : "Not logged in text 2"></div>
    ....
</div>

Is there a way to store operations on user role or authority in a local variable?


Solution

  • Updated: You can use ${#authorization.expression('hasAuthority(...)')} to evaluate in Thymeleaf:

            <div class=container th:with="isUser = ${#authorization.expression('hasAuthority(''USER'')')}"...
              ...
    

    Alternatively, you can access the authorities through an expression (iterating over a Collection):

            <th:block th:each="authority : ${#authentication.authorities}">
              ...
            </th:block>
    

    ${#authentication} is an implementation of Authentication.

    Updated example:

            <p th:text="${#authentication}"/>
            <th:block th:each="authority : ${#authentication.authorities}">
              <div th:text="${authority}"></div>
            </th:block>
    

    Generates:

            <p>org.springframework.security.authentication.UsernamePasswordAuthenticationToken@1a6c9e86: Principal: org.springframework.security.core.userdetails.User@8892938c: Username: [email protected]; Password: [PROTECTED]; Enabled: true; AccountNonExpired: true; credentialsNonExpired: true; AccountNonLocked: true; Granted Authorities: ADMINISTRATOR,USER; Credentials: [PROTECTED]; Authenticated: true; Details: org.springframework.security.web.authentication.WebAuthenticationDetails@fffbcba8: RemoteIpAddress: 0:0:0:0:0:0:0:1; SessionId: A031D4B4CAB26223C13AE9B30AA62212; Granted Authorities: ADMINISTRATOR, USER</p>
    
              <div>ADMINISTRATOR</div>
    
              <div>USER</div>