Issue
I am creating a website using Spring Boot for the first time. I am using a test page to show that once the user has logged in, the words, "Authenticated" to appear on the screen when the user has logged in.
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org"
xmlns:sec="http://www.thymeleaf.org/extras/spring-security">
<head>
<meta charset="utf-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge"/>
<meta name="viewport" content="width=device-width, initial-scale=1"/>
</head>
<body>
<h2>Thymleaf example</h2>
<p sec:authorize="hasRole('ROLE_USER')">
Authenticated
</p>
</body>
</html>
However, problem is that the tag with the sec:authorize remains unedited and unparsed. As a result, the Authenticated word appears regardless of whether a user logged in or not. Printing the user's authorities from controller confirms this.
my pom.xml file has the following dependencies.
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.thymeleaf.extras</groupId>
<artifactId>thymeleaf-extras-springsecurity4</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
... dependencies for mysql and jdbc are omitted.
Any help is appreciated. Note, I am using Spring Boot, so JAVA configurations are preferred over XML configurations.
Solution
Please try adding something like the following code to your @Configuration
(or @SpringBootApplication
) class:
@Bean
public SpringTemplateEngine templateEngine(ITemplateResolver templateResolver, SpringSecurityDialect sec) {
final SpringTemplateEngine templateEngine = new SpringTemplateEngine();
templateEngine.setTemplateResolver(templateResolver);
templateEngine.addDialect(sec); // Enable use of "sec"
return templateEngine;
}
Note that if you are forcing Spring Boot to use Thymeleaf version 3, you have to force also the version 3 of the thymeleaf-extras-springsecurity4
dependency:
<dependency>
<groupId>org.thymeleaf.extras</groupId>
<artifactId>thymeleaf-extras-springsecurity4</artifactId>
<version>3.0.1.RELEASE</version>
</dependency>
See also this related answer.
Answered By - Robert Hume