Token Customization and Identity Extraction
Explore how to customize JSON Web Tokens (JWTs) in Spring Security by embedding domain-specific claims like roles into access tokens. Learn to safely extract this identity data at the resource server using the @AuthenticationPrincipal annotation, enabling stateless, fine-grained authorization in APIs. This lesson guides you through the token customization lifecycle, modern bean-based injection techniques, and integrating these patterns for secure identity management and testing in Spring-based 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 ...