解决Spring Boot Security – Thymeleaf sec:authorize-url 标签不生效

2018 年 6 月 5 日 2 条评论 15.46k 次阅读 7 人点赞

用 SpringBoot + SpringSecurity + Thymeleaf 搭建了一个应用,发现 Thymeleaf sec:authorize-url 以及 sec:authorize="hasRole('ROLE_ADMIN')" 标签都不生效。
后来发现是 Maven 引入 thymeleaf-extras-springsecurity4 时没有指定版本号,直接使用是SpringBoot的版本。

解决方案:

在maven中把 thymeleaf-extras-springsecurity4 改成

<!--springsecurity4 要指定3.0以上版本,否则权限标签可能无法工作-->
<dependency>
    <groupId>org.thymeleaf.extras</groupId>
    <artifactId>thymeleaf-extras-springsecurity4</artifactId>
    <version>3.0.2.RELEASE</version>
</dependency>

然后 thymeleaf 模板中就可以这样使用了:


<div sec:authorize="isAuthenticated()">
  This content is only shown to authenticated users.
</div>


<div sec:authorize="hasRole('ROLE_ADMIN')">
  This content is only shown to administrators.
</div>


<div sec:authorize="hasRole('ROLE_USER')">
  This content is only shown to users.
</div>

 
<div sec:authorize-url="/admin/foo">
    can see /admin
 </div>



Logged user: <span sec:authentication="name">Bob</span>
Roles: <span sec:authentication="principal.authorities">[ROLE_USER, ROLE_ADMIN]</span>

后续又发现一个问题。在新版的springboot 2.1.x 中也会导致标签失效,暂时先用2.0.7及以下吧。

雷雷

这个人太懒什么东西都没留下

文章评论(2)

  • 熊乃奇

    大佬 我这边找个问题 也没生效 还清楚其他原因吗?

    2018 年 12 月 12 日
    • 雷雷

      @熊乃奇 我那个原因是引用 thymeleaf-extras-springsecurity4 时没有指定版本。后来指定了3.0.2.RELEASE就可以了。应该是版本兼容问题。另外最新版的 springboot 2.1.x 也会有问题。建议用 2.0.x

      2018 年 12 月 22 日
  • (Spamcheck Enabled)