我是第一次使用
Spring Boot创建一个网站.我正在使用测试页面显示一旦用户登录,当用户登录时,屏幕上会出现“Authenticated”字样.
<!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>
但是,问题是带有sec:authorize的标签仍然未经编辑和未解析.因此,无论用户是否登录,都会显示Authenticated字.从控制器打印用户的权限确认了这一点.
我的pom.xml文件具有以下依赖项.
<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.
任何帮助表示赞赏.
注意,我使用的是Spring Boot,因此JAVA配置比XML配置更受欢迎.
最佳答案 请尝试在@Configuration(或@SpringBootApplication)类中添加类似以下代码的内容:
@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;
}
请注意,如果您强制Spring Boot使用Thymeleaf版本3,您还必须强制使用thymeleaf-extras-springsecurity4依赖项的版本3:
<dependency>
<groupId>org.thymeleaf.extras</groupId>
<artifactId>thymeleaf-extras-springsecurity4</artifactId>
<version>3.0.1.RELEASE</version>
</dependency>