如何创建自定义 JwtGrantedAuthoritiesConverter 以从特定声明中获取角色。
我正在使用 Spring Security 6 和授权服务器来验证不透明访问令牌。我想根据内省响应中的“access”字段填充权限。
自省回应:
{
"username": "user_test",
"scope": "STANDARD",
"access": [
"CUSTOM_ROLE_111",
"CUSTOM_ROLE_222",
"CUSTOM_ROLE_333",
"CUSTOM_ROLE_444",
],
"name": "acessor",
"active": true,
"loginType": "PASSWORD",
"refreshToken": "$2b$10$s...",
"iat": 1692016676,
"exp": 1692103076
}
我尝试过:
@Bean
public Converter<Jwt, AbstractAuthenticationToken> jwtAuthenticationConverter() {
return jwt -> {
List<GrantedAuthority> authorities = new ArrayList<>();
List<String> accessScopes = jwt.getClaimAsStringList("access");
for (String scope : accessScopes) {
authorities.add(new SimpleGrantedAuthority("SCOPE_" + scope));
}
return new JwtAuthenticationToken(jwt, authorities);
};
}
然后:
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http
.authorizeHttpRequests(authorize -> authorize
.anyRequest().authenticated()
)
.oauth2ResourceServer(oauth ->
oauth.opaqueToken(opaqueTokenConfigurer ->
opaqueTokenConfigurer.introspector(opaqueTokenIntrospector())));
return http.build();
}
Bu根本不起作用。发生几个 BeanCreationException
知道如何解决这个问题吗?
基本上,据我所知,到目前为止,通过创建自定义的customJwtGrantedAuthoritiesConvert还需要为JwtDecoder公开一个Bean。从文档到公开 JwtDecoder @Bean 我需要 jwk。因为我正在使用内省,所以我没有 jwk。
我的日志:2023-08-15T15:42:09.555+03:00 ERROR 3828 --- [ main] o.s.b.d.LoggingFailureAnalysisReporter :
应用程序无法启动
描述:
org.springframework.security.config.annotation.web.configuration.WebSecurityConfiguration 中方法 setFilterChains 的参数 0 需要一个类型为“org.springframework.security.oauth2.jwt.JwtDecoder”的 bean,但无法找到。
参考:https://docs.spring.io/spring-security/reference/servlet/oauth2/resource-server/jwt.html
您还需要声明 JWTDecoder bean。
像下面这样..
@Bean
public JwtDecoder jwtDecoder() {
return NimbusJwtDecoder.withIssuerLocation(TOKEN_ISSUE_URL).build();
}
您还可以使用 JwkURI、SecretKey 和公钥创建 JwtDecoder bean。