Thymeleaf 3.0 Spring Boot + Security integration does not work

前端 未结 3 730
执念已碎
执念已碎 2021-01-18 13:19

I struggle to get Thymeleaf to work with Spring Security in my Spring Boot 1.4.3 based project.

Tags like e.g.

相关标签:
3条回答
  • 2021-01-18 13:38

    I used to have the same problem. Thymeleaf SpringSecurity only works with versions 3.x.x of thymeleaf, and the version that's shipped with Spring-boot is something like 2.x.x atm.

    Looking up how to add v3.x.x to my project brought me to the following documentation page: http://docs.spring.io/spring-boot/docs/current/reference/htmlsingle/#howto-use-thymeleaf-3

    So you just need to add your dependencies, and then add the following in your properties to override the default version of thymeleaf to your dependencies:

    <thymeleaf.version>3.0.2.RELEASE</thymeleaf.version>
    <thymeleaf-layout-dialect.version>2.1.1</thymeleaf-layout-dialect.version>
    
    0 讨论(0)
  • 2021-01-18 13:40

    To get it working, if you are using Thymeleaf 3.0.2 with Spring Boot 1.4, you need to force version 3.0.1.RELEASE of thymeleaf-extras-springsecurity4 (because it inherits version 2.1.2 which does not work in combination with Thymeleaf 3):

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

    The tags should be using the hasRole function.

    <div sec:authorize="hasRole('ROLE_ADMIN')">
    
    0 讨论(0)
  • 2021-01-18 14:02

    If you use 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>
    

    you need just the following dependencies:

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

    Version of thymeleaf-extras-springsecurity4 will be inherited from the spring-boot-starter-parent and would be 3.0.2.RELEASE.

    Thanks to @yglodt for pointing this out.


    Also in your templates add spring-security namespace xmlns:sec="http://www.thymeleaf.org/extras/spring-security" and use hasRole instead of hasAuthority value in <sec:authorize> tag:

    <div sec:authorize="hasRole('ROLE_ADMIN')">
        ...
    </div>
    
    0 讨论(0)
提交回复
热议问题