Skip to content
AITroveRead. Build. Understand.
Make this comfortable

Spring Security JWT tenant principal: map only a validated claim

Last updated: 30 Sept 20264 min read
tutorial
IntermediateBy AITrove Editorial

A JWT tenant principal is an identity value taken from a validated token claim, not from a request header or URL segment.

Download Spring source kit

The converter has a trust precondition

The source-kit web context verifies a locally signed JWT, its issuer, audience, expiry and required tenant_id claim before the JWT authentication converter uses tenant_id as the principal name. The token has subject reviewer-41, yet the tenant service sees tenant-east. That distinction is intentional: user identity and tenant ownership are different fields, even when an application chooses a tenant claim for this narrow fixture.

The path /contract/tenant/tenant-east returns the east row. A request for tenant-west with the same token returns 403. Sending X-Tenant: tenant-west does not change the principal. The base JWT lesson checks token trust and scope without tenant mapping; the query lesson checks the database side of this boundary.

Choose a claim contract before coding

A signature proves who issued the token, not that every claim was assigned by an authorized tenant registry. The issuer must define tenant membership, rotation and revocation rules. A production system may use a stable subject plus a separately checked tenant membership service instead of treating tenant_id as the principal. Do not accept a caller-selected tenant header as a replacement for that trust decision.

Checked source

Java
var converter = new JwtAuthenticationConverter();
converter.setPrincipalClaimName("tenant_id");
http.oauth2ResourceServer(resource -> resource.jwt(jwt ->
    jwt.decoder(decoder).jwtAuthenticationConverter(converter)));

Verification boundary

JwtTenantBoundaryTest.trustedTenantClaimPassesTheMatchingServiceRule and JwtTenantBoundaryTest.anotherTenantIsForbiddenAfterAuthentication runs in the downloadable Spring source kit. The excerpt is shortened; the kit contains the complete test.

Costs and limits

The test uses ephemeral RSA keys and a local web context. It does not contact an identity provider, check JWKS rotation or model users with membership in multiple tenants. Signature verification and database lookup add per-request CPU and I/O respectively; cache any derived membership only with a revocation policy.

Common Mistakes

  • Do not trust X-Tenant as an identity source.
  • Do not confuse token subject with tenant ownership.
  • Do not map an unvalidated optional claim into the principal.

Read next

Spring Security JWT resource server: validate trust before checking scope, Spring JWT tenant claims: reject missing or malformed ownership before conversion, Spring JdbcTemplate tenant predicates: put ownership in the SQL query, Spring method authorization: reject a cross-tenant read.

spring
spring-boot
jwt-tenant-principal
Storage details