【问题标题】:Disable/Enable Html element based on Role Springboot+Thymeleaf基于角色 Springboot+Thymeleaf 禁用/启用 Html 元素
【发布时间】:2018-05-21 20:09:38
【问题描述】:

我有一个具有多个角色(ROLE1、ROLE2)的安全 springboot 应用程序。一位用户同时具有两种角色,而另一位用户只有一种。成功登录后,用户将被发送到登录页面,如果用户只有一个角色,我想在那儿禁用元素。

我尝试过 thymeleaf-extras-springsecurity3 但没有成功。这是我的代码:

Pom.xml

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

landing.html(尝试了所有选项)

!${currentUser.user.hasAuthority('ROLE1')}
!${#authorization.expression('hasRole('ROLE1')')}
${#authentication.getPrincipal().getUser().getRoles()}
${#authentication.getPrincipal().getRoles()}

但是没有成功,我总是得到像这样的对象的空错误

org.springframework.expression.spel.SpelEvaluationException: EL1011E: Method call: Attempted to call method getPrincipal() on null context object

任何帮助将不胜感激!谢谢!

【问题讨论】:

    标签: java spring spring-security thymeleaf


    【解决方案1】:

    我认为recommended的方式是使用xmlns:sec="http://www.thymeleaf.org/extras/spring-security"命名空间来达到你想要的结果sec:authorize="hasRole('ROLE_ADMIN')"

    <html xmlns:th="http://www.thymeleaf.org" 
          xmlns:sec="http://www.thymeleaf.org/extras/spring-security">
    <head>...</head>
    <body>
        <div sec:authorize="hasRole('ROLE_ADMIN')">...</div>
    
        // or use #authorization, but use escape quote 'hasRole(''ROLE_USER'')'
        <div th:if="${#authorization.expression('hasRole(''ROLE_USER'')')}">...</div>
    </body>
    

    您可能(我认为 spring-boot 默认会这样做)还必须配置 SpringSecurityDialect 才能使其工作。

     @Bean
    public TemplateEngine templateEngine() {
        SpringTemplateEngine engine = new SpringTemplateEngine();
        engine.setTemplateResolver(templateResolver());
        engine.addDialect(securityDialect());
        return engine;
    }
    
    private IDialect securityDialect(){
        SpringSecurityDialect dialect = new SpringSecurityDialect();
        return dialect;
    }
    

    也可以看看类似的问题:Spring Security hasRole() not working

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-08-10
      • 2020-05-27
      • 2016-07-03
      • 1970-01-01
      • 2014-11-27
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多