Thymeleaf弹簧安全

时间:2016-05-20 10:48:12

标签: spring spring-security thymeleaf

我一直在尝试检查当前用户是否与百里香 - 额外 - 弹簧安全有任何特定的角色

<dependencies>

<dependency>
  <groupId>org.thymeleaf.extras</groupId>
  <artifactId>thymeleaf-extras-springsecurity3</artifactId>
  <version>2.1.2.RELEASE</version>
</dependency>

在servletcontext.xml

<bean id="templateEngine" class="org.thymeleaf.spring4.SpringTemplateEngine">
      <property name="additionalDialects">
        <set>
          <bean class="org.thymeleaf.extras.springsecurity3.dialect.SpringSecurityDialect"/>
        </set>
      </property>
    </bean>

在我看来,我一直在尝试

    <!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org">
<body>
  <!-- Template page showcasing C-EASY graphic elements -->
  <div th:fragment="content">
    home
    <div sec:authorize="hasAuthority('ROLE_PORTEFEUILLE')">Show ROLE_PORTEFEUILLE</div>
    <div sec:authorize="hasAuthority('ROLE_BOITEAOUTIL')">Show ROLE_BOITEAOUTIL.</div>

    <div sec:authorize="hasAuthority('ROLE_SIMULER')">Show ROLE_SIMULER</div>
    <div sec:authorize="hasAuthority('ROLE_SOUSCRIRE')">ShowROLE_SOUSCRIRE.</div>


     <div sec:authorize="hasRole('ROLE_ADMINTESTING')">
        This will only be displayed if authenticated user has role ROLE_ADMIN.
    </div>

    <div sec:authorize="isAuthenticated()">THis user is authenticated </div>

<div sec:authorize="isAnonymous()">This user is anonymous </div>

<div sec:authentication="name">
    The value of the "name" property of the authentication object should appear here.
</div> 

<div sec:authorize="hasRole('ROLE_ADMIN')">
    This content is only shown to administrators.
</div>



  </div>
</body>
</html>

当前用户拥有除 ROLE_BOITEAOUTIL 以外的所有角色。

home
Show ROLE_PORTEFEUILLE
Show ROLE_BOITEAOUTIL.
Show ROLE_SIMULER
ShowROLE_SOUSCRIRE.
Show ROLE_SIMULER_TEST

仅当经过身份验证的用户具有角色ROLE_ADMIN时才会显示。

THis user is authenticated
This user is anonymous
The value of the "name" property of the authentication object should appear here.

此内容仅向管理员显示。

如何同时对用户进行身份验证和匿名? 似乎 hasRole(role)每次都返回true。 什么可能是错的,我该如何调试呢?

2 个答案:

答案 0 :(得分:0)

  

似乎hasRole(role)每次都返回true。

这可能是因为您忘记了模板文件中的sec命名空间。

<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org" xmlns:sec="http://www.springframework.org/security/tags">

如果在输出文件中你仍然看到'sec:authorize =“hasRole('ROLE_ADMIN')”'那么你的方言配置有问题。

如果不是那么你必须调试。负责这些方法的类是

org.springframework.security.access.expression.SecurityExpressionRoot

扩展了SecurityExpressionOperations接口

只需在要测试的任何方法上添加断点,并查看结果为何如此。

boolean isAnonymous();
boolean isAuthenticated();
boolean isRememberMe();
boolean hasRole(String role);
boolean hasAnyRole(String... roles);
boolean hasAuthority(String authority);
...
and others

答案 1 :(得分:0)

尝试将此添加到您的<html>

xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity3"

如果不起作用,请尝试使用hasAuthority('<somerole>')