I struggle to get Thymeleaf to work with Spring Security in my Spring Boot 1.4.3 based project.
Tags like e.g.
<div sec:authorize="hasAuthority('ADMIN')">
are simply not parsed.
If I try to add the SpringSecurityDialect
manually like this:
@Bean
public SpringSecurityDialect securityDialect() {
return new SpringSecurityDialect();
}
I am getting:
Exception in thread "main" java.lang.NoClassDefFoundError: org/thymeleaf/dialect/IExpressionEnhancingDialect
I have included the following in my dependencies:
<dependency>
<groupId>org.thymeleaf.extras</groupId>
<artifactId>thymeleaf-extras-springsecurity4</artifactId>
</dependency>
The SpringSecurityDialect
does not seem to be added by the autoconfiguration.
After I add the Bean manually, I get the mentioned exception.
Is this a bug or am I missing something?
My Thymeleaf versions are:
<thymeleaf.version>3.0.2.RELEASE</thymeleaf.version>
<thymeleaf-extras-java8time.version>3.0.0.RELEASE</thymeleaf-extras-java8time.version>
<thymeleaf-layout-dialect.version>2.1.2</thymeleaf-layout-dialect.version>
To get it working, if you are using Thymeleaf
3.0.2 with Spring Boot 1.4, you need to force version 3.0.1.RELEASE
of thymeleaf-extras-springsecurity4
(because it inherits version 2.1.2 which does not work in combination with Thymeleaf 3):
<dependency>
<groupId>org.thymeleaf.extras</groupId>
<artifactId>thymeleaf-extras-springsecurity4</artifactId>
<version>3.0.1.RELEASE</version>
</dependency>
The tags should be using the hasRole
function.
<div sec:authorize="hasRole('ROLE_ADMIN')">
If you use Spring Boot 2.0.0.RELEASE:
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.0.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
you need just the following dependencies:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.thymeleaf.extras</groupId>
<artifactId>thymeleaf-extras-springsecurity4</artifactId>
</dependency>
Version of thymeleaf-extras-springsecurity4
will be inherited from the spring-boot-starter-parent
and would be 3.0.2.RELEASE
.
Thanks to @yglodt for pointing this out.
Also in your templates add spring-security namespace xmlns:sec="http://www.thymeleaf.org/extras/spring-security"
and use hasRole
instead of hasAuthority
value in <sec:authorize>
tag:
<div sec:authorize="hasRole('ROLE_ADMIN')">
...
</div>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With