Spring OAuth2 资源服务器 - 用户名属性未反映在 SecurityContextHolder 中
Spring OAuth2 Resource Server - user-name-attribute not reflected in SecurityContextHolder
我在我的 JWT 中有一个名为 user_name
的声明,并且相应的 user-name-attribute
在 spring security oauth2 client provider proper 属性 中设置为 user_name
:
spring.security.oauth2.client.provider.my-oauth-provider.user-name-attribute=user_name
我还可以看到 属性 正被 ReactiveClientRegistrationRepository
class (ClientRegistration.ProviderDetails.UserInfoEndpoint
) 正确读取。但是当我在资源服务器 上阅读 SecurityContextHolder.getContext().getAuthentication().getName()
时,我可以看到从(默认)sub
- IdTokenClaimNames.SUB
声明中获取的值。
这是为什么?我是否仍然错过了资源服务器端的一些额外配置,以指定 user-name-attribute
由资源服务器上的 SecurityContextHolder.getContext().getAuthentication().getName()
获取和返回?我知道只有 Bearer 令牌(可能还有一些 cookie)从客户端发送到资源服务器,所以 Gateway/client 端可能还需要一些其他过滤器 - 只是猜测?
原因是您正在使用前缀为 security.oauth2.client
的 属性,它适用于 OAuth 2.0 客户端。
在 Spring Security 5.2.x 中,没有 Spring Boot 属性 来指示资源服务器的用户名属性,例如security.oauth2.resourceserver.xyz
您可以将自己的 Converter
发布到 DSL,但是:
JwtAuthenticationConverter converter = new JwtAuthenticationConverter();
http
.oauth2ResourceServer()
.jwtAuthenticationConverter(jwt -> {
JwtAuthenticationToken authentication = converter.convert(jwt);
return new JwtAuthenticationToken(authentication.getToken(),
authentication.getAuthorities(), jwt.getClaim("claim"));
});
我在我的 JWT 中有一个名为 user_name
的声明,并且相应的 user-name-attribute
在 spring security oauth2 client provider proper 属性 中设置为 user_name
:
spring.security.oauth2.client.provider.my-oauth-provider.user-name-attribute=user_name
我还可以看到 属性 正被 ReactiveClientRegistrationRepository
class (ClientRegistration.ProviderDetails.UserInfoEndpoint
) 正确读取。但是当我在资源服务器 上阅读 SecurityContextHolder.getContext().getAuthentication().getName()
时,我可以看到从(默认)sub
- IdTokenClaimNames.SUB
声明中获取的值。
这是为什么?我是否仍然错过了资源服务器端的一些额外配置,以指定 user-name-attribute
由资源服务器上的 SecurityContextHolder.getContext().getAuthentication().getName()
获取和返回?我知道只有 Bearer 令牌(可能还有一些 cookie)从客户端发送到资源服务器,所以 Gateway/client 端可能还需要一些其他过滤器 - 只是猜测?
原因是您正在使用前缀为 security.oauth2.client
的 属性,它适用于 OAuth 2.0 客户端。
在 Spring Security 5.2.x 中,没有 Spring Boot 属性 来指示资源服务器的用户名属性,例如security.oauth2.resourceserver.xyz
您可以将自己的 Converter
发布到 DSL,但是:
JwtAuthenticationConverter converter = new JwtAuthenticationConverter();
http
.oauth2ResourceServer()
.jwtAuthenticationConverter(jwt -> {
JwtAuthenticationToken authentication = converter.convert(jwt);
return new JwtAuthenticationToken(authentication.getToken(),
authentication.getAuthorities(), jwt.getClaim("claim"));
});