Token Customization and Identity Extraction
Explore how to customize OAuth 2.0 JWT access tokens by adding domain-specific claims like user roles, and learn how to extract this identity data securely at resource servers using Spring Security. Understand the token lifecycle, the use of OAuth2TokenCustomizer, and effective identity extraction methods that support stateless and decoupled microservice architectures.
We'll cover the following...
Generating an access token is only the first step in a complete authorization architecture. Out of the box, a standard JSON Web Token (JWT) issued by Spring Authorization Server contains basic protocol claims like subject, issuer, and expiration. However, enterprise applications often require domain-specific identity data in these tokens, such as user roles, tenant identifiers, or display names. By embedding this data directly into the JWT, downstream resource servers can make localized security decisions without repeatedly querying a central database.
We will explore how to safely inject this custom data into our tokens and securely extract it at the API boundary.
The life cycle of custom claims
In legacy Spring Security implementations, developers modified token payloads using the TokenEnhancer interface and interacted heavily with OAuth2Authentication objects. We no longer use these deprecated components. Modern Spring Authorization Server uses a context-aware injection model driven by customizer beans.
To build a secure flow, we must trace the life cycle of a custom claim across our architecture. The authorization server reads the users details from a database during login, injects specific attributes into the JWT payload, and signs the token. The client then presents this token to the resource server, which validates the signature, maps the embedded claims to security authorities, and passes the identity down to the protected API controller.
The following logical diagram ...