spring - 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>
有没有办法将用户角色或权限的操作存储在局部变量中?
解决方案
更新:您可以使用${#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>
推荐阅读
- css - 复选框的离子选择 UI
- python - 翻转字符串中的二进制文件
- firebase - 只允许某些主机访问我的 Firebase Cloud Function
- c# - 为什么运行时不打印日志“End-Test”,但在调试时打印?
- performance - BS4:如何将 find_all 减少到最低限度(忽略而不是提取)
- android - 我们如何知道以编程方式在 android 设备中注册了多少指纹..以便只允许在应用程序中使用选定的指纹
- cmake - find_package 静态库而不是共享库
- python - string.replace() 定义它时向我输出错误
- android - 如何在相对路径中从 MediaStore 读取文件?
- python - 如何使用 Selenium 和 Python 上传文件