Spring Security解析含scp前缀的JWT时Scope为空,如何自定义解析?
解决Spring Security解析JWT时识别scp作为Scope别名的问题
可以通过自定义JWT认证转换器,指定Spring Security使用scp字段作为Scope的来源,具体步骤如下:
1. 自定义JwtAuthenticationConverter
创建自定义转换器,配置JwtGrantedAuthoritiesConverter以识别scp字段:
import org.springframework.security.core.GrantedAuthority; import org.springframework.security.oauth2.jwt.Jwt; import org.springframework.security.oauth2.server.resource.authentication.JwtAuthenticationConverter; import org.springframework.security.oauth2.server.resource.authentication.JwtGrantedAuthoritiesConverter; public class CustomJwtAuthenticationConverter extends JwtAuthenticationConverter { public CustomJwtAuthenticationConverter() { JwtGrantedAuthoritiesConverter authoritiesConverter = new JwtGrantedAuthoritiesConverter(); // 将scope字段指定为JWT中的"scp" authoritiesConverter.setScopeAttributeName("scp"); // 可选:修改权限前缀,默认是"SCOPE_",如果不需要可以设为空字符串 // authoritiesConverter.setAuthorityPrefix(""); setJwtGrantedAuthoritiesConverter(authoritiesConverter); } }
2. 在资源服务器配置中使用自定义转换器
修改Spring Security配置,让OAuth2资源服务器使用这个自定义转换器解析JWT:
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.web.SecurityFilterChain; @Configuration @EnableWebSecurity public class ResourceServerConfig { @Bean public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception { http .authorizeHttpRequests(auth -> auth .anyRequest().authenticated() ) .oauth2ResourceServer(oauth2 -> oauth2 .jwt(jwt -> jwt .jwtAuthenticationConverter(new CustomJwtAuthenticationConverter()) ) ); return http.build(); } }
补充说明
- 不管JWT中的
scp是单个字符串(如"scp": "read_notifications.v1")还是数组格式(如"scp": ["read", "write"]),转换器都能自动解析并生成对应的GrantedAuthority。 - 默认生成的权限会带上
SCOPE_前缀,如果不需要这个前缀,取消注释代码中的setAuthorityPrefix("")即可。
内容的提问来源于stack exchange,提问作者Timothy Vogel
相关产品推荐
相关产品推荐

