Spring Thymeleaf集成Spring Security时sec:authentication标签失效问题求助
我仔细看了你的问题描述,控制台能正常输出登录用户名,但Thymeleaf页面上的sec:authentication标签就是不生效,显示默认的"Username",这确实是个常见的配置问题,核心原因有两个:版本冲突和命名空间配置错误,下面给你一步步解决:
1. 先解决最关键的版本冲突问题
你POM里的Spring Boot parent用的是3.0.0-SNAPSHOT(快照版本),但却手动指定了spring-boot-starter-security为2.7.0,同时搭配thymeleaf-extras-springsecurity5,这完全不兼容!Spring Boot 3.x对应的是Spring Security 6.x,而thymeleaf-extras-springsecurity5只支持Spring Security 5.x,版本不匹配直接导致Thymeleaf无法解析sec标签。
给你两个可行的方案:
方案A:降级到稳定的Spring Boot 2.7.x版本
把parent的版本改成2.7.x的最新稳定版,和你用的Security版本匹配:
<parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.7.15</version> <!-- 2.7系列的最新稳定版 --> <relativePath/> </parent>
这样你的spring-boot-starter-security:2.7.0和thymeleaf-extras-springsecurity5:3.0.4.RELEASE就能完美兼容了。
方案B:升级到Spring Boot 3.x稳定版并匹配对应依赖
如果想保留Spring Boot 3.x,就得把依赖都升级到对应版本:
- 去掉
spring-boot-starter-security的手动版本,让parent自动管理(Spring Boot 3.x默认搭配Spring Security 6.x) - 把
thymeleaf-extras-springsecurity5替换为thymeleaf-extras-springsecurity6(适配Spring Security 6.x)
修改后的依赖片段:
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-security</artifactId> <!-- 移除version,让parent自动匹配 --> </dependency> <dependency> <groupId>org.thymeleaf.extras</groupId> <artifactId>thymeleaf-extras-springsecurity6</artifactId> <!-- 也可以手动指定适配的版本,比如3.1.1.RELEASE --> </dependency>
注意Spring Boot 3.x要求Java 17+,你已经配置了java.version=17,这部分没问题。
2. 修正Thymeleaf的sec命名空间
你当前用的命名空间xmlns:sec="https://www.thymeleaf.org/thymeleaf-extras-springsecurity5"确实是错误的,访问这个链接会返回404,Thymeleaf根本识别不了这个命名空间,自然不会处理标签内容。
不管你用上面哪个方案,正确的sec命名空间都是:
<html lang="en" xmlns:th="http://www.thymeleaf.org" xmlns="http://www.w3.org/1999/html" xmlns:sec="http://www.thymeleaf.org/extras/spring-security">
替换掉你原来的命名空间配置即可。
3. 最后验证配置
修改完成后,重启项目,登录测试一下你的页面代码:
<div sec:authorize="isAuthenticated()"> Welcome <span sec:authentication="name">Username</span> </div>
现在应该能正常显示登录的用户名了。另外,你控制器里能正常获取Authentication说明Security上下文是正常的,问题就出在Thymeleaf的sec标签解析环节,上面的修改应该能彻底解决。
内容的提问来源于stack exchange,提问作者iank

