百里香叶 3.0 春季启动 + 安全集成不起作用



我很难让Thymeleaf在我的基于Spring Boot 1.4.3的项目中使用Spring Security。

标签,例如

<div sec:authorize="hasAuthority('ADMIN')">

根本无法解析。

如果我尝试像这样手动添加SpringSecurityDialect

@Bean
public SpringSecurityDialect securityDialect() {
return new SpringSecurityDialect();
}

我得到:

Exception in thread "main" java.lang.NoClassDefFoundError: org/thymeleaf/dialect/IExpressionEnhancingDialect

我在我的依赖项中包含以下内容:

<dependency>
<groupId>org.thymeleaf.extras</groupId>
<artifactId>thymeleaf-extras-springsecurity4</artifactId>
</dependency>

自动配置似乎没有添加SpringSecurityDialect

手动添加 Bean 后,我得到提到的异常。

这是一个错误还是我错过了什么?

我的百里香叶版本是:

<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>

要使其正常工作,如果您将Thymeleaf3.0.2 与 Spring Boot 1.4 一起使用,则需要强制使用thymeleaf-extras-springsecurity4的版本3.0.1.RELEASE(因为它继承了不能与 Thymeleaf 3 结合使用的版本 2.1.2):

<dependency>
<groupId>org.thymeleaf.extras</groupId>
<artifactId>thymeleaf-extras-springsecurity4</artifactId>
<version>3.0.1.RELEASE</version>
</dependency>

标记应使用hasRole函数。

<div sec:authorize="hasRole('ROLE_ADMIN')">

如果你使用 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>

您只需要以下依赖项:

<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>

thymeleaf-extras-springsecurity4的版本将从spring-boot-starter-parent继承,并且3.0.2.RELEASE

感谢@yglodt指出这一点。


同样在您的模板中添加 spring-security 命名空间xmlns:sec="http://www.thymeleaf.org/extras/spring-security"并使用hasRole而不是<sec:authorize>标记中的hasAuthority值:

<div sec:authorize="hasRole('ROLE_ADMIN')">
...
</div>

我曾经有同样的问题。 Thymeleaf SpringSecurity仅适用于3.x.x版本的thymeleaf,而Spring-boot附带的版本类似于2.x.x atm。

查找如何将 v3.x.x 添加到我的项目中,我来到了以下文档页面: http://docs.spring.io/spring-boot/docs/current/reference/htmlsingle/#howto-use-thymeleaf-3

因此,您只需要添加依赖项,然后在属性中添加以下内容,以将 thymeleaf 的默认版本覆盖到依赖项中:

<thymeleaf.version>3.0.2.RELEASE</thymeleaf.version>
<thymeleaf-layout-dialect.version>2.1.1</thymeleaf-layout-dialect.version>

最新更新