基于角色 Springboot+Thymeleaf 禁用/启用 Html 元素

vib*_*e93 2 java spring spring-security thymeleaf

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

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

xml文件

...
<dependency>
            <groupId>org.thymeleaf.extras</groupId>
            <artifactId>thymeleaf-extras-springsecurity3</artifactId>
            <version>3.0.2.RELEASE</version>
        </dependency>
...
Run Code Online (Sandbox Code Playgroud)

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

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

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

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

任何帮助将非常感激!谢谢!

var*_*ren 7

我认为推荐的方法是使用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>
Run Code Online (Sandbox Code Playgroud)

您可能(我认为 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;
}
Run Code Online (Sandbox Code Playgroud)

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