liveBook · Manning

JWT authentication converter

As explained in Spring Security in Action, Second Edition

A JWT authentication converter is a converter that transforms a decoded JWT into an application-specific authentication object.

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

How Spring Security in Action, Second Edition covers it

How deep it goes
Explains the custom class, converter, registration, endpoint exposure, and verification sequence.
Examples
Uses a priority claim, CustomAuthentication, a read authority, and a /demo response containing priority HIGH.
What it assumes
Assumes basic JWT resource-server configuration and teaches custom authentication objects and converters incrementally.
What you can do after
Build it from scratch by translating JWT claims into a custom authentication object and wiring it into resource-server security.
How it connects
Connects JWT, OAuth 2 resource servers, authentication objects, security contexts, claims, and authorization.

This explainer was generated by Manning's knowledge graph from the text of Spring Security in Action, Second Edition. The section links point to the parts of the book it draws on.