迁移至Spring Security 6后Granted Authority列表为空求助
问题分析与解决方案
1. 替换废弃的权限配置API
Spring Security 6中authorizeRequests()已被废弃,必须改用authorizeHttpRequests(),否则部分授权配置无法生效。
2. 自定义JWT转换器提取Azure AD权限
Azure AD返回的JWT中,角色通常存于roles(应用角色)或scp(委派权限)字段,默认的JwtBearerTokenAuthenticationConverter不会自动将这些字段转换为GrantedAuthority,需自定义转换器:
@Bean public JwtAuthenticationConverter jwtAuthenticationConverter() { JwtGrantedAuthoritiesConverter authoritiesConverter = new JwtGrantedAuthoritiesConverter(); // 指定从roles字段提取权限,前缀可根据业务需求调整 authoritiesConverter.setAuthoritiesClaimName("roles"); authoritiesConverter.setAuthorityPrefix("ROLE_"); JwtAuthenticationConverter converter = new JwtAuthenticationConverter(); converter.setJwtGrantedAuthoritiesConverter(authoritiesConverter); return converter; }
之后在SecurityFilterChain中引用该转换器:
.oauth2ResourceServer(oauth2 -> oauth2 .jwt(jwt -> jwt.jwtAuthenticationConverter(jwtAuthenticationConverter())) );
3. 修正过滤器添加位置
你的代码中将过滤器添加逻辑嵌套在authorizeRequests的链式调用内,这是错误的。需将过滤器配置直接放在HttpSecurity的链式调用中:
@Bean public SecurityFilterChain filterChain(HttpSecurity http) throws Exception { log.debug("Configuring HTTP Security"); http .csrf(csrf -> csrf.disable()) .cors() .and() .headers(headers -> headers.frameOptions(frame -> frame.disable())) .sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS)) .exceptionHandling() .and() // 调整过滤器添加位置,直接挂载到HttpSecurity .addFilterBefore(new RolesToRightsConverterFilter(s3RSpringConfig), BasicAuthenticationFilter.class) .addFilterAfter(new Slf4jMDCFilter(authService, tracingService), RolesToRightsConverterFilter.class) .authorizeHttpRequests(auth -> auth .requestMatchers(HttpMethod.GET, "/sf/**", "/assets/**", "/resources/**", "/built/**", "/ui/**").permitAll() .anyRequest().authenticated() ) .oauth2ResourceServer(oauth2 -> oauth2 .jwt(jwt -> jwt.jwtAuthenticationConverter(jwtAuthenticationConverter())) ); return http.build(); }
4. 解决Azure AD配置冲突
你的application.yml同时配置了Spring Security原生OAuth2资源服务器和Azure AD Starter的参数,存在配置优先级冲突。建议统一使用Azure AD Starter的配置:
cloud: azure: active-directory: credential: client-id: ${add_client_id:xxx} client-secret: xxx profile: tenant-id: ${add_tenant_id:xxx} resourceserver: jwt: enabled: true jwk-set-cache-lifespan: 10m jwk-set-cache-refresh-time: 10m
同时删除Spring Security原生的security.oauth2.resourceserver配置项。
5. 匿名用户权限配置(可选)
若需要给匿名用户分配默认权限,可添加如下配置:
.authorizeHttpRequests(auth -> auth .requestMatchers(HttpMethod.GET, "/sf/**", "/assets/**", "/resources/**", "/built/**", "/ui/**").permitAll() .anonymous().authorities("ROLE_ANONYMOUS") .anyRequest().authenticated() )
内容的提问来源于stack exchange,提问作者Wash
相关产品推荐
相关产品推荐

