Spring Security 6.0 移除了 WebSecurityConfigurerAdapter,配置 JWT 认证过滤器链需通过定义 SecurityFilterChain Bean 实现,适用于基于 Token 的无状态认证场景,风险在于旧配置方式完全不可用且 JWT 解析需自行引入依赖。
先说结论:Spring Security 6.0 强制使用 SecurityFilterChain Bean 配置安全链,JWT 过滤器需手动注册在 UsernamePasswordAuthenticationFilter 之前。
- 适合:Spring Boot 3.x 搭配 Spring Security 6.x 的新建项目或迁移项目。
- 先准备:确认 JDK 版本升至 17 及以上,移除 WebSecurityConfigurerAdapter 相关继承代码。
- 验收:通过 curl 发送带 Token 请求返回 200,不带 Token 请求返回 401。
快速处理思路
无需执行 shell 命令,需在 Maven 或 Gradle 中引入安全依赖,并在配置类中编写 Bean 定义。
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt-api</artifactId>
</dependency>为什么会这样
Spring Security 6.0 重构了配置模型,废弃并移除了 WebSecurityConfigurerAdapter 类。
旧版本通过继承适配器类覆盖 configure 方法配置安全链,6.0 版本改为直接定义 SecurityFilterChain 类型的 Bean。这种变化强制开发者使用组件化配置,解决了配置类继承层级过深的问题,但导致旧代码无法编译。JWT 功能并非 Spring Security 核心模块内置,需结合第三方库或 OAuth2 Resource Server 模块实现解析与验证。
分步处理
第一步:创建 JWT 工具类与过滤器。
编写 JwtUtil 处理 Token 生成与解析,创建 JwtAuthenticationFilter 继承 OncePerRequestFilter。在 doFilterInternal 方法中解析 Header 中的 Token,成功则设置 SecurityContext 中的 Authentication 对象。
第二步:定义 SecurityFilterChain Bean。
在配置类中使用 @Bean 注解定义 SecurityFilterChain。调用 http.authorizeHttpRequests 配置放行登录接口,其余请求需认证。使用 http.addFilterBefore 将 JWT 过滤器注册在 UsernamePasswordAuthenticationFilter 之前。
第三步:配置密码编码器与认证管理器。
定义 PasswordEncoder Bean 用于密码加密。若需支持账号密码登录,需配置 AuthenticationManager Bean 并在登录接口调用 authenticate 方法。
怎么验证是否生效
使用 curl 命令访问受保护接口,不带 Authorization 头应返回 401 Unauthorized。
带上正确的 Bearer Token 应返回 200 OK 及业务数据。检查后端日志,确认 JWT 过滤器已执行且 SecurityContext 中已存入用户信息。
常见坑
跨域请求 OPTIONS 预处理未被放行,导致前端请求被拦截。需在 http.cors 中启用跨域配置并配合 CorsConfigurationSource。
登录接口未排除认证过滤,导致无法获取 Token。需在 authorizeHttpRequests 中对登录路径设置 permitAll。
Token 解析异常未捕获,导致过滤器链中断。需在 JwtAuthenticationFilter 中捕获异常并返回 401,避免抛出异常至容器层。
常见问题
Spring Security 6.0 还能用 WebSecurityConfigurerAdapter 吗?
不能,该类在 6.0 版本已被移除,必须改用 SecurityFilterChain Bean 配置方式。
JWT 解析库必须用 JJWT 吗?
不是,也可使用 nimbus-jose-jwt 或 Spring Security OAuth2 Resource Server 内置的 JWT 支持。
过滤器顺序写错会有什么影响?
若 JWT 过滤器在 UsernamePasswordAuthenticationFilter 之后,可能导致表单登录优先执行而跳过 Token 验证。
参考来源
Spring Security Reference Documentation, Spring Security 6.0 Migration Guide, https://spring.io/projects/spring-security