2

i have a secured springboot application with multiple roles (ROLE1,ROLE2). One user has both roles and the other one has only one. On successful login user is sent to the landing page, over there i want to disable element if user has only one role.

I've tried with thymeleaf-extras-springsecurity3 but with no success. This is my code:

Pom.xml

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

landing.html (tried with all of the options)

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

But with no success, i always get null error for that object like this

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

Any help would be much appreciated! Thanks!

vibetribe93
  • 257
  • 8
  • 23

1 Answers1

8

I think the recommended way is to use xmlns:sec="http://www.thymeleaf.org/extras/spring-security" namespace to achieve the result you want 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>

You will probably (I think spring-boot does it by default) also have to configure SpringSecurityDialect to make it work.

 @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;
}

Also take a look at similar question: Spring Security hasRole() not working

varren
  • 14,551
  • 2
  • 41
  • 72