Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Thymeleaf 3.0 Spring Boot + Security integration does not work

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>
like image 484
yglodt Avatar asked Dec 29 '16 22:12

yglodt


2 Answers

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')">
like image 144
yglodt Avatar answered Sep 29 '22 08:09

yglodt


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>
like image 43
DimaSan Avatar answered Sep 29 '22 06:09

DimaSan