Why a Valid JWT Can Still Let the Wrong Tenant In
Implement a JWT validation boundary that checks issuer, audience, required claims, tenant ownership, and current permissions before authorizing an action.
Series: Json Web Tokens (2 articles)
- 1Why a Valid JWT Can Still Let the Wrong Tenant In This article
The token is valid. The invoice belongs to another tenant. If the API returns it anyway, the signing algorithm has done its job and the authorization boundary has failed.
Think of a signed employee badge. It can establish who issued the badge and which person it describes. It doesn't establish that this person may open every room in the building. I'd keep those two decisions visibly separate in code: validate the token, then authorize the requested resource.
We'll use an invoice API as the example. A token carries a tenant identifier and an
invoices:read permission. The request names an invoice. The server must connect those facts through a trusted validation policy and a tenant-scoped data lookup.Define the token profile before accepting tokens
JWT best current practices call for appropriate algorithm verification, issuer and audience validation, and distinct validation rules for different token uses. A token issued by a trusted organization can still be intended for another API or for an identity flow rather than API access.
For this application, I would configure a trusted issuer, expected audience, allowed signing algorithm, and verification keys together. An incoming
kid can select among that issuer's configured keys; it cannot choose an arbitrary key server or file path. ID tokens and access tokens need separate acceptance rules.The sample below uses a pinned RSA public key passed by trusted application configuration. A real identity-provider integration should implement that provider's documented key-discovery and rotation contract. Don't derive the algorithm allowlist from the token header.
import jwt
ISSUER = 'https://identity.example.test/'AUDIENCE = 'invoice-api'
def validate_access_token(token, public_key): claims = jwt.decode( token, public_key, algorithms=['RS256'], issuer=ISSUER, audience=AUDIENCE, leeway=5, options={ 'require': ['iss', 'aud', 'sub', 'exp', 'iat', 'tenant_id'] }, ) tenant = claims['tenant_id'] if not isinstance(tenant, str) or not tenant: raise jwt.InvalidTokenError('invalid tenant_id') permissions = claims.get('permissions', []) if not isinstance(permissions, list) or not all( isinstance(value, str) for value in permissions ): raise jwt.InvalidTokenError('invalid permissions') return claims
def invoice_query(claims, invoice_id): if 'invoices:read' not in claims.get('permissions', []): raise PermissionError('permission required') return ( 'SELECT id, total_cents FROM invoices ' 'WHERE tenant_id = ? AND id = ?', (claims['tenant_id'], invoice_id), )The query uses SQLite parameter syntax to make the example executable locally. Adapt placeholders to the database driver, preserving parameter binding and both predicates. Tenant selection comes from validated claims; invoice ownership is checked by the database query itself. An untrusted request parameter cannot override it.
PyJWT's API reference distinguishes requiring claims from checking their values. Requiring
exp makes absence an error; expiry verification checks its meaning. The five-second leeway here is an illustrative clock-skew allowance, not extra session lifetime to hand out without review. Custom claims still require application-specific validation.Claims are snapshots with a publication date
Suppose an administrator removes
invoices:read at 10:02. A token issued at 10:00 still contains the permission. Its signature establishes that the issuer signed those bytes, not that the permission is current at 10:03.I'd choose the freshness rule by operation. A low-risk read might accept a short-lived snapshot. A permission change, export, or money-moving action may need a current entitlement check. If that check is cached, its maximum stale interval is part of the authorization design.
Changing the token payload on the client is not a refresh strategy. The issuer must produce a new token, and the resource server must decide what to do with older ones. Likewise, a
jti identifies a token; it doesn't make the token single-use unless a verifier records and enforces consumption.Keep the payload small and the trust boundaries clear
A signed JWT payload is usually readable by whoever holds it. A signature provides integrity and authentication under the configured trust model; it doesn't provide payload confidentiality. Avoid putting secrets or unnecessary personal information into access tokens. TLS protects transport, but tokens can still appear in application logs, diagnostic tools, or client storage.
Algorithm choice is also a key-distribution decision. With HS256, anyone holding the shared verification secret can also mint tokens. With an asymmetric scheme, a verifier can hold only the public key. That separation is useful across services. It doesn't make a weak authorization policy strong, nor establish that every RSA configuration is categorically more secure than every HMAC configuration.
Test tokens that are valid in the wrong context
Generate test fixtures with a temporary RSA key pair. Keep the private key only in the test process. The important negative tests should include a correctly signed token with the wrong audience, a correctly signed token from the wrong issuer, a missing expiry, an expired token beyond skew allowance, an invalid tenant type, and an absent permission.
Then create two invoices with the same identifier under different tenants in a disposable database. The query must return only the row belonging to the validated tenant. This catches a class of application bugs that signature tests cannot see.
The sample was exercised with PyJWT 2.15.1 and a temporary local RSA key pair. The claim-validation and tenant-scoped query checks ran locally; no identity provider or deployed API was involved.
Conclusion
I'd put a token-profile validator at the API boundary and a resource-specific authorization check at the data boundary. Review both when adding a new claim. The useful question is whether a valid token can be used in the wrong context, and the answer should be demonstrated by a failing request test.
Adapted and substantially updated from my original article . Technical references reviewed November 8, 2026. Prepared with AI assistance; examples and validation limits are identified in the text.
Series: Json Web Tokens (2 articles)
- 1Why a Valid JWT Can Still Let the Wrong Tenant In This article
Enjoyed reading this content? Let the author know!
Your likes, comments, shares, and saves help creators reach more builders.
Loading recommendations
Loading article