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.