You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Spring Boot 3.3.x中Thymeleaf的sec:authentication标签不显示求助

问题原因及解决方案

1. 表达式大小写错误

你编写的sec:authentication="Principal.Username"和Principal.authorities存在大小写问题:

  • Spring Security中,principal为小写(对应SecurityContext里的Authentication.getPrincipal())
  • UserDetails的用户名属性是username(对应getUsername()方法,遵循JavaBean规范的小写开头)
  • 正确写法应为:
<div>
    you are logged as <b sec:authentication="principal.username"></b> with a role:
    <span sec:authentication="principal.authorities"></span>
</div>

也可以直接用sec:authentication="name"获取用户名(对应Authentication.getName()),用sec:authentication="authorities"获取权限列表。

2. 依赖版本不匹配

Spring Boot 3.3.x对应Spring Security 6,需确保引入适配的Thymeleaf Spring Security扩展依赖:

Maven配置:

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

Gradle配置:

implementation 'org.thymeleaf.extras:thymeleaf-extras-springsecurity6'

Spring Boot依赖管理会自动匹配对应版本,无需手动指定,但要注意避免引入旧版的springsecurity5依赖。

3. 确认Thymeleaf Spring Security方言生效

虽然Spring Boot会自动配置方言,但若仍有问题,可显式配置确保生效:

@Configuration
public class ThymeleafConfig {
    @Bean
    public SpringSecurityDialect springSecurityDialect() {
        return new SpringSecurityDialect();
    }
}

4. 确认页面被Thymeleaf处理

确保HTML页面放在src/main/resources/templates目录下,通过Spring MVC控制器返回(如return "index"),而非直接静态访问,这样Thymeleaf才能解析方言标签。


内容的提问来源于stack exchange,提问作者9527 snl

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.11 09:33:08