首页 > 解决方案 > Thymeleaf Spring Security - 将身份验证存储到本地变量中

问题描述

我在我的 Spring Boot 项目中使用 Thymeleaf Spring Security。

在 html 文件中,我连续多次检查以根据用户角色(管理员、用户、未登录)显示文本。

<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>

我知道您可以在 Thymeleaf 中使用局部变量。我想将权限检查保存到局部变量中,以便以后可以编写更有效的代码。下面的例子,但是局部变量部分显然是不正确的。

<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>

有没有办法将用户角色或权限的操作存储在局部变量中?

标签: springspring-bootthymeleaf

解决方案


更新:您可以使用${#authorization.expression('hasAuthority(...)')}Thymeleaf 进行评估:

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

或者,您可以通过表达式访问权限(迭代集合):

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

${#authentication}是一个实现Authentication

更新示例:

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

生成:

        <p>org.springframework.security.authentication.UsernamePasswordAuthenticationToken@1a6c9e86: Principal: org.springframework.security.core.userdetails.User@8892938c: Username: admin@example.com; 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>

推荐阅读