1

I have a claim named user_name within my JWT and also corresponding user-name-attribute set as user_name in spring security oauth2 client provider proper property:

spring.security.oauth2.client.provider.my-oauth-provider.user-name-attribute=user_name

I can also see this property is properly being read by ReactiveClientRegistrationRepository class (ClientRegistration.ProviderDetails.UserInfoEndpoint). But when I read SecurityContextHolder.getContext().getAuthentication().getName() on Resource Server I can see the value taken from (default) sub - IdTokenClaimNames.SUB claim.

Why is that? Do I still miss some additional configuration also on resource server side to have specified user-name-attribute taken and returned by SecurityContextHolder.getContext().getAuthentication().getName() on Resource Server? I understand that only Bearer token (and maybe some cookies) is being sent from client to resource server so maybe also some other filter is needed on Gateway/client side - just guessing?

m52509791
  • 449
  • 5
  • 13

1 Answers1

1

The reason is that you are using a property prefixed with security.oauth2.client, which is intended for OAuth 2.0 Clients.

In Spring Security 5.2.x, there is no Spring Boot property to indicate a user name attribute to Resource Server, e.g. security.oauth2.resourceserver.xyz

You could publish your own Converter to the DSL, though:

JwtAuthenticationConverter converter = new JwtAuthenticationConverter();

http
    .oauth2ResourceServer()
        .jwtAuthenticationConverter(jwt -> {
            JwtAuthenticationToken authentication = converter.convert(jwt);
            return new JwtAuthenticationToken(authentication.getToken(), 
                    authentication.getAuthorities(), jwt.getClaim("claim"));
        });
jzheaux
  • 7,042
  • 3
  • 22
  • 36
  • 1
    Thanks for your answer - just added casting to `JwtAuthenticationToken` and it works fine. I added further thoughts on that issue on https://github.com/spring-projects/spring-security/issues/7757 mostly around the idea of having `spring.security.oauth2.resourceserver.jwt.user-name-attribute` also on resourceserver side so it is being hanlded automatically with kind of consistency on both (client and resource server ends). Thanks again! – m52509791 Dec 20 '19 at 06:57