Spring Security中OAuth2ResourceServerConfigurer::jwt弃用及API变更咨询
Spring Security 6.x 下JWT资源服务器配置及请求匹配替代方案
一、OAuth2ResourceServerConfigurer::jwt 的正确用法
你的现有代码中http.oauth2ResourceServer(OAuth2ResourceServerConfigurer::jwt)本身是有效的,只要配置文件里正确指定了JWT issuer URI等核心参数(比如spring.security.oauth2.resourceserver.jwt.issuer-uri=https://你的认证服务器地址),就能完成基础的JWT验证。
如果需要自定义JWT解码逻辑、权限转换规则等,要通过lambda表达式展开配置:
@Bean SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception { http .authorizeHttpRequests(auth -> auth.anyRequest().authenticated()) .sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS)) .httpBasic(Customizer.withDefaults()) .csrf(csrf -> csrf.disable()) .headers(headers -> headers.frameOptions(frame -> frame.sameOrigin())) .oauth2ResourceServer(oauth2 -> oauth2 .jwt(jwt -> jwt // 自定义JWT解码器,比如基于JWK Set URI .decoder(customJwtDecoder()) // 自定义JWT声明到权限的转换规则 .jwtAuthenticationConverter(customJwtAuthConverter()) ) ); return http.build(); } // 示例:配置JWK Set URI的JwtDecoder @Bean JwtDecoder customJwtDecoder() { return JwtDecoders.fromIssuerLocation("https://your-auth-server.com"); } // 示例:自定义JWT权限转换 @Bean JwtAuthenticationConverter customJwtAuthConverter() { JwtGrantedAuthoritiesConverter authoritiesConverter = new JwtGrantedAuthoritiesConverter(); authoritiesConverter.setAuthorityPrefix("ROLE_"); // 给权限添加前缀 authoritiesConverter.setAuthoritiesClaimName("roles"); // 指定存储权限的JWT声明字段 JwtAuthenticationConverter converter = new JwtAuthenticationConverter(); converter.setJwtGrantedAuthoritiesConverter(authoritiesConverter); return converter; }
二、Spring Security 6.x 请求匹配的替代方案
6.0版本移除了antMatchers()、mvcMatchers()、regexMatchers(),统一使用requestMatchers(),支持多种匹配场景:
1. Ant风格路径匹配(替代antMatchers)
直接传入路径字符串即可,默认采用Ant风格匹配规则:
http.authorizeHttpRequests(auth -> auth .requestMatchers("/public/**", "/login").permitAll() .anyRequest().authenticated() );
2. MVC路由匹配(替代mvcMatchers)
如果需要贴合Spring MVC的路由规则(比如考虑@RequestMapping的全局前缀),可以使用MvcRequestMatcher:
@Autowired private HandlerMappingIntrospector handlerMappingIntrospector; http.authorizeHttpRequests(auth -> auth .requestMatchers(new MvcRequestMatcher(handlerMappingIntrospector, "/api/**")).authenticated() .anyRequest().permitAll() );
3. 正则路径匹配(替代regexMatchers)
使用RegexRequestMatcher实现正则匹配:
http.authorizeHttpRequests(auth -> auth .requestMatchers(new RegexRequestMatcher("^/api/\\d+/.*$", null)).authenticated() .anyRequest().permitAll() );
4. 组合多种匹配规则
可以链式调用requestMatchers(),也可以在单个方法中传入多种类型的匹配器:
http.authorizeHttpRequests(auth -> auth .requestMatchers("/public/**").permitAll() .requestMatchers(new MvcRequestMatcher(handlerMappingIntrospector, "/user/**")).hasRole("USER") .requestMatchers(new RegexRequestMatcher("^/admin/.*$", null)).hasRole("ADMIN") .anyRequest().authenticated() );
内容的提问来源于stack exchange,提问作者Yogesh Rao
相关产品推荐
相关产品推荐

