Thymeleaf 如何通过 th:security-* 属性访问 Spring Security 的认证和授权信息?

解读

国内一线互联网公司(阿里、美团、京东等)在 Spring Boot 单体或微服务前端渲染场景里,普遍用 Thymeleaf 做“服务端拼装 + SEO”。面试官问“th:security-*”并不是考你背标签,而是验证三件事:

  1. 你是否真的整合过 Spring Security,而不是只用过拦截器;
  2. 你是否理解“自然模板”原则——不能为了权限把 HTML 弄得无法预览;
  3. 你是否能在数据层面做“细粒度”控制(按钮级、行级、菜单级),而不是简单地在 Controller 做跳转。

因此,回答要围绕“标签用法 → 表达式 → 安全上下文 → 性能 → 前后端协同”展开,体现工程级思考。

知识点

  1. 依赖与方言:thymeleaf-extras-springsecurity5(或 6)jar 必须显式引入;注册 SpringSecurityDialect,Thymeleaf 才能识别 th:sec 前缀。
  2. 三大核心属性: th:sec:authorize="expression" —— 标签级条件渲染,表达式返回 true 才输出整个标签; th:sec:authorize-expr="expression" —— 与上面等价,只是属性名不同,用于避免冲突; th:sec:authentication="property" —— 把 Authentication 对象里的属性直接绑定到文本或 value。
  3. 表达式语法:使用 Spring Security 内置的 hasRole、hasAuthority、hasPermission、isAuthenticated()、principal 等,支持 SpEL 运算符 and/or/!。
  4. 安全上下文:背后调用 SecurityContextHolder.getContext(),与业务线程绑定;页面渲染阶段只读,不会触发懒加载或 SQL,性能损耗极低。
  5. 自然模板:未登录时浏览器看到的是不带敏感按钮的静态原型;设计师用 Dreamweaver 打开也不会报错,符合国内“产品—设计—前端—后端”并行流程。
  6. 与 URL 重写结合:th:href="@{/admin/user}" 配合 th:sec:authorize 可以做到“既看不见也点不到”,比单纯前端隐藏更安全。
  7. 常见坑:① 只加 spring-boot-starter-security 没加 extras 导致前缀不识别;② 把 ROLE_ 前缀写死两次导致角色匹配失效;③ 在异步模板解析(邮件、PDF)里用 sec:* 出现上下文为空,需要手动设置 SecurityContext。

答案

步骤一:引入依赖(Maven 示例)

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

Spring Boot 3.x 用 6;2.x 用 5。Gradle 把坐标换成 implementation 即可。

步骤二:注册方言(Spring Boot 自动配置已做,可跳过;非 Boot 项目需手动)

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

步骤三:在模板文件 html 标签声明 sec 命名空间

<html xmlns:th="http://www.thymeleaf.org"
      xmlns:sec="http://www.thymeleaf.org/extras/spring-security">

步骤四:获取登录用户信息

<span sec:authentication="name">匿名</span>
<span sec:authentication="principal.authorities">加载中…</span>
<input type="hidden" th:value="${#authentication.principal.userId}" />

说明:sec:authentication 支持直接写属性路径,也可用 Thymeleaf 内置 #authentication 对象。

步骤五:细粒度授权

<button th:sec:authorize="hasRole('ADMIN')">删除用户</button>
<tr th:each="item : ${list}" th:sec:authorize-expr="${item.ownerId == #authentication.principal.userId or hasRole('ADMIN')}">
    <td th:text="${item.title}">标题</td>
</tr>

说明:表达式里既可以调 Spring Security 内置函数,也能访问业务变量,实现“行级”控制。

步骤六:菜单级复用——配合 th:replace 片段

<div th:replace="~{fragments/menu :: adminMenu}" th:sec:authorize="hasAuthority('system:manage')"></div>

未授权时整个 div 不会被渲染,也不会触发 SQL 查询,性能最优。

步骤七:与 CSRF、URL 重写协同

<form th:action="@{/logout}" method="post" th:sec:authorize="isAuthenticated()">
    <button>退出</button>
</form>

Thymeleaf 会自动追加 _csrf 参数,sec 属性保证未登录时连表单都不输出,彻底杜绝“隐藏按钮还能被构造请求”的风险。

通过以上七步,Thymeleaf 在渲染期就能完成“认证信息读取 + 授权判断”,无需前端 JavaScript 参与,兼顾 SEO、安全和设计体验。

拓展思考

  1. 性能调优:当页面存在大量 sec:authorize 判断时,可开启 Thymeleaf 模板缓存并在开发阶段使用 spring.thymeleaf.cache=false;上线后缓存命中率为 100%,解析耗时 < 1 ms。
  2. 微服务网关场景:如果前端经过 Nginx + Gateway + 单体,常见做法是在 Gateway 把 JWT 解析成 X-User-Id、X-Role 头,单体里用 SecurityContextHolderAwareRequestWrapper 构造预认证令牌,Thymeleaf 侧代码无需改动,实现“一次编写,多处复用”。
  3. 数据权限与 sec:* 分工:页面按钮用 sec 控制可见性;数据行用 MyBatis Plus 的数据权限插件在 SQL 追加条件;两者互补,避免“前端隐藏但接口泄露”。
  4. 测试策略:在 MockMvc 测试中使用 @WithMockUser、@WithUserDetails 注解,配合 HtmlUnit 断言页面上某个按钮是否存在,确保权限标签真正生效,而不是“看起来隐藏了其实能被访问”。
  5. 未来趋势:随着 SSR + Island 架构回潮,Thymeleaf 与 htmx、Alpine.js 组合成为“轻量 Node 替代方案”;sec:* 属性依旧适用,但需要注意 WebFlux 环境使用 thymeleaf-extras-springsecurity6 的 ReactiveSecurityContextHolder 适配器,避免阻塞线程。

掌握这些深度细节,你在面试中就能从“会用”升级到“能优化、能落地、能带队”,稳稳拿到 Offer。