2 回答

TA貢獻1785條經驗 獲得超8個贊
就我而言,使用“Spring Security 5”和“thymeleaf-extras-springsecurity4”導致了這個問題。如果您使用的是 Spring Security 5,請改用“thymeleaf-extras-springsecurity5”。(最近發布了“thymeleaf-extras-springsecurity5”)

TA貢獻1875條經驗 獲得超5個贊
通過挖掘越來越多的解決方案,我找到了一個適合我的解決方案:
不能有
web.ignoring().antMatchers("/");
at 之類的東西SecurityConfig.configure()
。
即,您要應用“授權過濾器”的頁面不得設置為被安全忽略。使用
sec:authorize
,而不是sec:authentication
(這會導致誤差)index.html
。
工作index.html:
<!DOCTYPE html>
<html
xmlns:th="http://www.thymeleaf.org"
xmlns:sec="http://www.thymeleaf.org/extras/spring-security">
<head>
<meta charset="UTF-8"/>
<title>bla bla bla</title>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" rel="stylesheet"/>
</head>
<body style="text-align: center;">
<div sec:authorize="true">
authorize - always
</div>
<div sec:authorize="false">
authorize - never
</div>
<div class="container" sec:authorize="isAnonymous()">
authorize - anonymous
</div>
<div class="container" sec:authorize="!isAnonymous()">
authorize - not anonymous
</div>
<div class="container" sec:authorize="isAuthenticated()">
authorize - authenticated
</div>
<div class="container" sec:authorize="!isAuthenticated()">
authorize - not authenticated
</div>
<strong> Username: <span sec:authentication="name"></span> </strong>
<div th:text="${#authorization.getAuthentication()}">1</div>
<div th:text="${40}">1</div>
<!-- end of content! -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js"></script>
</body>
</html>
結果:(登錄時)
授權 - 始終
授權 - 非匿名
授權 - 認證
用戶名:test2
org.springframework.security.authentication.UsernamePasswordAuthenticationToken@00000000:委托人:....
40
(未登錄時)
授權 - 始終
授權 - 匿名
授權 - 未認證
用戶名:anonymousUser
org.springframework.security.authentication.UsernamePasswordAuthenticationToken@00000000:委托人:....
40
添加回答
舉報