Search code examples
javaspring-bootspring-securitythymeleaf

sec:authorize does not work - Spring Boot 2, Thymeleaf 3, Thymeleaf Spring Security 5 integration package


I'm working with

  • Spring Boot 2.2.5
  • Thymeleaf 3.0.11
  • Thymeleaf Spring Security 5, 3.0.4 Release

I use the following dependencies in my pom.xml:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-security</artifactId>
</dependency>

<dependency>
    <groupId>org.thymeleaf.extras</groupId>
    <artifactId>thymeleaf-extras-springsecurity5</artifactId>
</dependency>

Versions are recognized and the respective jars are included in my project. I also have added the extra namespace of Thymeleaf Security Module to my templates:

<html xmlns:th="http://www.thymeleaf.org" xmlns:sec="http://www.thymeleaf.org/extras/spring-security">

I have implemented a role based authentication & authorization with Hibernate and MySQL and login / logout, which for my understanding works fine.

The sec:authentication tag of Thymeleaf Security Dialect works fine and also displays the correct roles. The sec:authorize tag seems to work as well when calling the method sec:authorize="isAuthenticated()". However, I'm struggling when evaluating the role of a user in the templates, both using sec:authorize="hasRole('...')" or th:if="${#authorization.expression('hasRole(''...'')')}". I seems that the roles cannot be evaluated although they are correctly displayed using sec:authentication="principal.authorities".

I have summarized my approaches on a test page, displaying the following result: showing image

Any clue where my bug or misunderstanding hides? Many thanks for your support in advance.


Solution

  • After some more research I figured out my issue. After adding the prefix ROLE_ to the role names (in the datasource), everything works fine.