如何获得Spring Boot来解析thymeleaf-extras-springsecurity标签?

nee*_*ame 5 spring spring-mvc thymeleaf spring-boot

我是第一次使用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配置。

Rob*_*ume 5

请尝试在您的@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;
}
Run Code Online (Sandbox Code Playgroud)

请注意,如果要强制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>
Run Code Online (Sandbox Code Playgroud)

另请参阅此相关答案