1. 概述

本文将快速介绍 Spring Security 与 Thymeleaf 的集成方案。我们将创建一个 Spring Boot 应用程序,演示安全方言(Security Dialect)的实际用法。

前端技术选择 Thymeleaf —— 这是一个现代的服务器端 Web 模板引擎,与 Spring MVC 框架集成良好。更多细节可参考我们的 入门文章

Spring Security 方言是 Thymeleaf 的官方扩展模块,专门用于简化两者的集成工作。

我们将基于 Spring Boot 教程 中的基础项目进行开发,同时参考 Thymeleaf 与 Spring 集成教程 中的标准配置。

2. 依赖配置

首先在 Maven 的 pom.xml 中添加新依赖:

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

⚠️ 建议始终使用最新版本,可在 Maven Central 获取。

3. Spring Security 配置

接下来定义 Spring Security 的核心配置。至少需要两个不同角色的用户来演示安全方言的用法:

@Configuration
@EnableWebSecurity
public class SecurityConfiguration {

    // [...] 
    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) 
      throws Exception {
        auth
          .inMemoryAuthentication()
          .withUser("user").password(passwordEncoder().encode("password")).roles("USER")
          .and()
          .withUser("admin").password(passwordEncoder().encode("admin")).roles("ADMIN");
    }
    
    @Bean
    public BCryptPasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }
}

configureGlobal() 方法中:

  • 创建了两个用户:user(USER角色)和 admin(ADMIN角色)
  • 使用 BCrypt 加密密码(生产环境必备)
  • 不同角色用于后续演示差异化内容展示

4. 安全方言详解

Spring Security 方言允许我们根据用户角色、权限或其他安全表达式条件化显示内容,同时提供对 Spring Authentication 对象的直接访问。

看下包含安全方言示例的首页:

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
    <head>
        <title>Welcome to Spring Security Thymeleaf tutorial</title>
    </head>
    <body>
        <h2>Welcome</h2>
        <p>Spring Security Thymeleaf tutorial</p>
        <div sec:authorize="hasRole('USER')">Text visible to user.</div>
        <div sec:authorize="hasRole('ADMIN')">Text visible to admin.</div>
        <div sec:authorize="isAuthenticated()">
            Text visible only to authenticated users.
        </div>
        Authenticated username:
        <div sec:authentication="name"></div>
        Authenticated user roles:
        <div sec:authentication="principal.authorities"></div>
    </body>
</html>

核心安全方言属性:

  • sec:authorize:权限控制
  • sec:authentication:认证信息访问

4.1 理解 sec:authorize

简单说,sec:authorize 用于控制页面内容的显示逻辑,常见用法:

按角色控制

<div sec:authorize="hasRole('USER')">仅用户可见</div>

认证用户通用控制

<div sec:authorize="isAuthenticated()">登录后可见</div>

⚠️ 支持所有 Spring Security 表达式,例如:

  • hasAuthority('PERMISSION_READ')
  • hasIpAddress('192.168.1.0/24')

4.2 理解 sec:authentication

Spring Security 的 Authentication 接口提供了丰富的认证信息访问方法。

在 Thymeleaf 中获取认证对象

<!-- 获取用户名 -->
<div sec:authentication="name"></div>

<!-- 获取用户角色 -->
<div sec:authentication="principal.authorities"></div>

常用属性:

  • name:用户名
  • principal.authorities:角色列表
  • credentials:凭证(敏感信息慎用)
  • details:认证详情(如登录IP)

5. 总结

本文通过 Spring Boot 应用演示了 Thymeleaf 中 Spring Security 方言的实用技巧,核心点包括:

  • 通过 sec:authorize 实现细粒度权限控制
  • 使用 sec:authentication 访问认证上下文
  • 基于角色的差异化内容展示

完整代码示例可在 GitHub 仓库 获取。


原始标题:Spring Security with Thymeleaf