A JWT authentication converter transforms a decoded JWT into an application-specific authentication object. It becomes useful when authorization needs custom claims, such as a token's priority, directly in the security context. section 15.2
Configure the customization in sequence:
- Define a custom authentication class extending JwtAuthenticationToken and add fields for application-specific claims. section 15.2
- Implement Converter<Jwt, CustomAuthentication>, read the priority claim, and construct the custom authentication object with its authorities. section 15.2
- Register the converter with the OAuth 2 resource server's JWT configuration. section 15.2
- Return Authentication from an endpoint to verify that the security context contains the custom field. section 15.2
Listing 15.9 Converting the access token to an authentication object
@Component
public class JwtAuthenticationConverter
implements Converter<Jwt, CustomAuthentication> {
@Override
public CustomAuthentication convert(Jwt source) {
List<GrantedAuthority> authorities =
List.of(() -> "read");
String priority = #1
String.valueOf(source.getClaims().get("priority"));
return new CustomAuthentication(source,
authorities,
priority); #2
}
}
Inspect the converter implementation that extracts a JWT claim and creates the custom authentication object. section 15.2
