堆疊:Spring Security 和 Thymeleaf。
我有以下問題:我想根據用戶的角色在所有 html 模板中顯示或不顯示某些元素。
所以,我在所有模板中都需要一個布爾變數“isAdmin”,以便我可以在條件下使用它:
<p th:if="${isAdmin}">Admin functionality</p>
請幫助我找到最佳解決方案。我嘗試了什么:
選項 1. 我可以在所有控制器的模型中添加變數。但我認為這是一個不好的做法。
選項 2。 我可以直接從會話中使用“th:with”將變數注入正文:
<body th:with="isAdmin=
${session
.SPRING_SECURITY_CONTEXT
.getAuthentication()
.getAuthorities()
.contains(T(com.example.model.enums.Role).ADMIN)}">
但是宣告太長了。我也沒有找到有關 Thymeleaf 中全域變數范圍的資訊。
選項 3。 我知道我應該在用戶會話中添加自定義屬性。我應該只在授權后添加一次。我想不出比覆寫successForwardUrl、在新控制器中添加屬性并重定向到主頁更好的方法了。
.formLogin()
.loginPage("/login").permitAll()
.successForwardUrl("/login/setAttributes")
@PostMapping ("login/setAttributes")
public String postLoginPage(HttpSession httpSession) {
boolean isAdmin = SecurityContextHolder
.getContext()
.getAuthentication()
.getAuthorities()
.contains(Role.ADMIN);
httpSession.setAttribute("isAdmin", isAdmin);
return "redirect:/";
}
但我仍然認為這不是最好的解決方案。
uj5u.com熱心網友回復:
看起來您正在尋找最佳解決方案
Thymeleaf 與 Spring Security 有其特殊的集成
你可以在這里查看檔案
首先,您應該org.thymeleaf.extras為您的專案添加依賴項:
<dependency>
<groupId>org.thymeleaf.extras</groupId>
<artifactId>thymeleaf-extras-springsecurity5</artifactId>
</dependency>
下一步。將 Thymeleafsec命名空間添加到您的.html模板中:
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:th="http://www.thymeleaf.org"
xmlns:sec="http://www.thymeleaf.org/extras/spring-security">
最后,您可以檢查用戶角色并顯示不同角色的特定內容:
<div sec:authorize="hasRole('ROLE_ADMIN')">
<p>Admin functionality</p>
</div>
也sec:authentication可用于檢索用戶名和角色:
<div sec:authorize="isAuthenticated()">
User: <span sec:authentication="name">User name</span>
Roles: <span sec:authentication="principal.authorities">User roles</span>
</div>
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/530883.html
