Thymeleaf:sec:在任何情况下都会显示身份验证,而sec:在任何情况下都不会授权

时间:2018-10-06 21:07:48

标签: java spring spring-security thymeleaf

无论是否登录,每个带有<div>的{​​{1}}都会显示。即使是明确的sec:authentication="..."也会导致false出现。

在另一侧,带有div的{​​{1}}被隐藏,即使有显式<div>

我尝试检查Maven依赖项,Spring MVC配置,sec:authorize="..."中的Spring Security Dialect和许多其他答案,但是没有适合我的情况的解决方案。

index.html

true

预期结果(如果未登录):

  

身份验证-始终

     

身份验证-匿名

     

身份验证-未通过身份验证

     

授权-始终

     

授权-匿名

     

授权-未验证

     

用户名:匿名

     

40

实际结果

  

身份验证-始终

     

身份验证-从不

     

身份验证-匿名

     

身份验证-非匿名

     

身份验证-已验证

     

身份验证-未通过身份验证

     

用户名:

     

40

2 个答案:

答案 0 :(得分:1)

就我而言,将“ Spring Security 5”与“ thymeleaf-extras-springsecurity4”一起使用会导致此问题。如果您使用的是Spring Security 5,请改用“ thymeleaf-extras-springsecurity5”。 (最近发布了“ thymeleaf-extras-springsecurity5”)

答案 1 :(得分:0)

通过挖掘越来越多的解决方案,我找到了一个适合我的解决方案:

  1. web.ignoring().antMatchers("/");一定不能有SecurityConfig.configure()之类的东西。
    即您必须将要应用“授权过滤器”的页面设置为不被安全忽略。
  2. 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