我正在尝试将Thymeleaf安全方言(例如sec:authorize标签)集成到正常工作的Spring Boot + Spring Security应用程序中.
经过一些研究后,我发现激活它的解决方案是:
在POM文件中添加依赖项:
<dependency>
<groupId>org.thymeleaf.extras</groupId>
<artifactId>thymeleaf-extras-springsecurity4</artifactId>
<version>3.0.0.RELEASE</version>
</dependency>
Run Code Online (Sandbox Code Playgroud)
并在模板文件的顶部包含标记:
<html xmlns:th="http://www.thymeleaf.org" lang="en"
xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity4">
Run Code Online (Sandbox Code Playgroud)
到现在为止还挺好.找到依赖关系,标记中标记的标记.
但是,它们不会被考虑在内并出现在生成的最终HTML中.
由于Spring Boot自动配置中的一个问题没有启用,似乎有必要手动将SpringSecurityDialect Bean 添加到一个@Configuration类来启用它(StackOverflow上的几个问题已经解决了):
@Bean
public SpringSecurityDialect securityDialect() {
return new SpringSecurityDialect();
}
Run Code Online (Sandbox Code Playgroud)
这就是导致问题的原因:当我将这个Bean添加到我的Spring Boot配置中时,它会引发异常,因为它找不到类org.thymeleaf.dialect.IProcessorDialect.这是错误:
> java.lang.IllegalStateException: Could not evaluate condition on
> org.springframework.boot.autoconfigure.PropertyPlaceholderAutoConfiguration#propertySourcesPlaceholderConfigurer
> due to org/thymeleaf/dialect/IProcessorDialect not found. Make sure
> your own configuration does not rely on that class. This can also
> happen if you are @ComponentScanning a springframework package (e.g.
> …Run Code Online (Sandbox Code Playgroud) 我是第一次使用Spring Boot创建一个网站。我正在使用一个测试页来显示用户登录后,用户登录后屏幕上会出现“已认证”字样。
<!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>
Run Code Online (Sandbox Code Playgroud)
但是,问题在于带有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.
Run Code Online (Sandbox Code Playgroud)
任何帮助表示赞赏。注意,我使用的是Spring Boot,因此JAVA配置优于XML配置。