一聚教程网:一个值得你收藏的教程网站

最新下载

热门教程

Spring Security 6+ JWT 配置正确用法详解

时间:2026-07-27 08:02:48 编辑:袖梨 来源:一聚教程网

Spring Security 6.x 已废弃 OAuth2ResourceServerConfigurer::jwt 等返回子配置器的方法,统一采用 Lambda 风格的 Customizer 方式配置 JWT 认证,本文详解迁移步骤与最佳实践。

spring security 6.x 已废弃 `oauth2resourceserverconfigurer::jwt` 等返回子配置器的方法,统一采用 lambda 风格的 `customizer` 方式配置 jwt 认证,本文详解迁移步骤与最佳实践。

在 Spring Security 6.0 及更高版本中,安全配置 DSL 进行了重大重构:为提升一致性与可读性,所有链式调用(如 .and())和返回独立 Configurer 实例的方法(如 http.oauth2ResourceServer(OAuth2ResourceServerConfigurer::jwt))均被标记为 deprecated。取而代之的是统一使用接受 Customizer<T> 的重载方法,通过 Lambda 表达式直接定制子模块行为。

这意味着你不能再写:

http.oauth2ResourceServer(OAuth2ResourceServerConfigurer::jwt); // ❌ 已废弃

而应改为显式调用 jwt() 方法,并传入 Customizer.withDefaults() 或自定义逻辑:

@BeanSecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {    http        .authorizeHttpRequests(authz -> authz            .anyRequest().authenticated() // ✅ 替代已移除的 antMatchers()/mvcMatchers()        )        .sessionManagement(session -> session            .sessionCreationPolicy(SessionCreationPolicy.STATELESS)        )        .httpBasic(Customizer.withDefaults()) // ✅ 替代已废弃的 httpBasic()        .csrf(csrf -> csrf.disable())        .headers(headers -> headers            .frameOptions(frameOptions -> frameOptions.sameOrigin())        )        .oauth2ResourceServer(oauth2 -> oauth2            .jwt(Customizer.withDefaults()) // ✅ 正确用法:Lambda + Customizer        );    return http.build();}

⚠️ 关键注意事项

  • Customizer.withDefaults() 并非“空操作”,它会启用默认 JWT 解析器(基于 NimbusJwtDecoder),自动从 jwk-set-uri(如 /oauth2/jwks)加载公钥;若需自定义解码器(如 RSA 公钥、本地密钥或响应式解码),请替换为 jwt(jwt -> jwt.decoder(myCustomDecoder))。
  • 所有请求匹配方法(antMatchers, mvcMatchers, regexMatchers)已在 6.0 中完全移除,必须使用 authorizeHttpRequests() 内部的 RequestAuthorizationManager 风格配置,例如:
    .requestMatchers("/public/**").permitAll().requestMatchers("/api/admin/**").hasRole("ADMIN")
  • 若集成 Spring Boot 3.x,请确保 spring-boot-starter-oauth2-resource-server 依赖版本 ≥ 3.0,并配置 spring.security.oauth2.resourceserver.jwt.jwk-set-uri 或 spring.security.oauth2.resourceserver.jwt.public-key-location。

✅ 总结:Spring Security 6+ 的核心原则是 “单一 DSL 路径” —— 全面拥抱函数式、不可变、Lambda 驱动的配置风格。及时更新 JWT 配置方式,不仅能消除编译警告,更能确保未来版本兼容性与配置语义清晰性。

热门栏目