1

I am new to spring security and spring authorization server. I wanted to customized the JWT access token to include additional parameter of userId within token generated.

I am using spring-authorization-server 1.0.0 and OAuth2TokenEndpointFilter is final class, hence unable to override it. Can someone guide me on which class needs to be configured or how this can be done?

Steve Riesenberg
  • 4,271
  • 1
  • 4
  • 26
deepti
  • 13
  • 3

1 Answers1

1

Take a look at the OAuth2TokenCustomizer in the reference. It gives access to the claims of the JWT before it is built, so you can customize however you need to.

Note that if you want to customize a specific token, this component is passed the context.getTokenType() so you can add an if-statement to only customize the access_token. See How-to: Customize the UserInfo Endpoint for an example (which customizes the id_token).


Update:

In order to add a dynamic value (such as a userId), you obviously would need to get the value to add. You might access the Principal associated with the authorization to do this, as in the following example:

@Bean
public OAuth2TokenCustomizer<JwtEncodingContext> tokenCustomizer() {
    return (context) -> {
        if (OAuth2TokenType.ACCESS_TOKEN.equals(context.getTokenType())) {
            UsernamePasswordAuthenticationToken authentication = context.getPrincipal();
            User user = (User) authentication.getPrincipal();

            context.getClaims().claim("userId", ((CustomUser) user).getId());
        }
    };
}

This assumes you created a CustomUser with an id.

If you need to look up a value, it's no different than any other Spring application. You should inject the bean you need to perform the lookup:

@Bean
public OAuth2TokenCustomizer<JwtEncodingContext> tokenCustomizer(CustomRepository repo) {
    return (context) -> {
        // ...
    };
}

How you use the injected bean is up to you. There are additional methods on the context such as context.getAuthorization() (returns the OAuth2Authorization) to get more context about the current authorization if needed.

Steve Riesenberg
  • 4,271
  • 1
  • 4
  • 26