Security & Identity
Securing REST APIs with JWT: Verification, Claims and Revocation
Advanced8 min readUpdated
A JSON Web Token is only as good as the verification performed on it, and the well-known JWT vulnerabilities are all failures of that verification rather than of the format. This guide covers JWS and JWE structure, algorithm allow-listing and key rotation with JWKS, the claims that must be checked, the revocation problem in stateless designs, where a browser should keep a token, and the controls a hardened API edge still needs.
What you will learn
- Explain JWS and JWE structure and what a signature does and does not prove
- Verify a token with an allow-listed algorithm and a key selected from JWKS by kid
- Validate iss, aud, exp, nbf and scope claims and reject anything missing
- Weigh stateless tokens against opaque tokens and design a workable revocation strategy
- Decide where a browser client should hold a token and how long it should live
- Layer rate limiting, input validation and resource-level authorization at the API edge
Token-based API security has a comfortable failure mode: everything works. A malformed token is rejected by the parser, a valid one lets the request through, and the integration is declared finished. What that does not exercise is the case the design exists for — an attacker supplying a token they crafted themselves. Nearly every published JWT vulnerability is a verification shortcut that only becomes visible under that test: an algorithm not pinned, a key chosen from the token's own header, an audience never compared, an expiry parsed but not enforced.
This guide is about doing the verifying side properly, and about the design questions that follow from choosing a stateless credential: how to revoke, how long a token should live, where a browser should keep it, and what else the API edge still owes you. How tokens are obtained is covered in OAuth 2.0, and the identity-specific ID token in OpenID Connect; here the token has already arrived in an Authorization header and the question is what to do with it.
What a JWT is made of
A JWT is a set of claims in JSON, serialised compactly. In the common JWS form it has three base64url segments separated by dots: header, payload, signature.
eyJhbGciOiJSUzI1NiIsInR5cCI6ImF0K2p3dCIsImtpZCI6InNpZy0yMDI2LTAzIn0
.eyJpc3MiOiJodHRwczovL3Nzby5leGFtcGxlLmNvbSIsInN1YiI6InUtODgyMzEiLCJhdWQiOiJodHRwczovL2FwaS5leGFtcGxlLmNvbSJ9
.QVhNc2lnbmF0dXJlYnl0ZXNnb2hlcmU
{ "alg": "RS256", "typ": "at+jwt", "kid": "sig-2026-03" }
{
"iss": "https://sso.example.com",
"sub": "u-88231",
"aud": "https://api.example.com",
"exp": 1789012645,
"nbf": 1789012340,
"iat": 1789012345,
"jti": "3f7c1e02-77aa-4f9c-9d31-2b6c0a5e77b1",
"scope": "orders.read orders.write",
"client_id": "web-portal"
}
Base64url is not a security measure — a browser-side JWT decoder or even a plain base64 decoder reads the payload instantly. Assume the client, and anyone who obtains the token, can read every claim, and never place internal identifiers, personal data or authorization hints in it that you would not print on the screen. typ: at+jwt marks the token explicitly as an OAuth access token, which is one defence against tokens intended for one purpose being accepted for another.
JWE is the encrypted alternative: five segments, with the payload encrypted to the recipient's key. It costs key management on the receiving side and is worth it only when claim confidentiality genuinely matters; a common middle path is a small opaque access token at the edge and a signed JWT inside the trust boundary.
Verifying the signature
The signature proves that a party holding the signing key produced this exact byte sequence and that it has not been altered. It proves nothing about whether the token was meant for you, whether it is still valid, or whether the user still exists. Getting the signature step right requires three specific decisions.
Allow-list the algorithm. Decide server-side which algorithms you accept and reject anything else, without consulting the token's alg header for permission. Two classic attacks depend on trusting that field: alg: none, where a library treats an empty signature as valid; and algorithm confusion, where a service configured for RS256 is handed a token signed with HS256 using the RSA public key as the HMAC secret — the public key is, after all, public. Both disappear when the verifier is constructed with a fixed algorithm.
Select the key by kid from a trusted key set. Never fetch a key from a URL supplied in the token's own header (jku) and never trust an embedded key (jwk). Fetch the issuer's JWKS from its discovery document, cache it, and refresh when an unknown kid appears — with a rate limit, so an attacker cannot force a fetch per request.
{
"keys": [
{ "kty": "RSA", "use": "sig", "alg": "RS256", "kid": "sig-2026-03",
"n": "wV5f8Q9c2u...", "e": "AQAB" },
{ "kty": "EC", "use": "sig", "alg": "ES256", "kid": "sig-2026-09",
"crv": "P-256", "x": "f83OJ3D2xF...", "y": "x_FEzRu9m36..." }
]
}
Prefer asymmetric signing. With RS256 or ES256 the resource server holds only the public key, so it can verify but not mint. HS256 shares one secret between issuer and every verifier, which means any verifier can forge tokens for the whole estate.
@Bean
JwtDecoder jwtDecoder(OAuth2ResourceServerProperties props) {
NimbusJwtDecoder decoder = NimbusJwtDecoder
.withJwkSetUri(props.getJwt().getJwkSetUri())
.jwsAlgorithms(algs -> { algs.add(SignatureAlgorithm.RS256); algs.add(SignatureAlgorithm.ES256); })
.build();
decoder.setJwtValidator(new DelegatingOAuth2TokenValidator<>(
new JwtTimestampValidator(Duration.ofSeconds(30)), // exp and nbf, bounded clock skew
new JwtIssuerValidator("https://sso.example.com"),
new JwtClaimValidator<List<String>>("aud",
aud -> aud != null && aud.contains("https://api.example.com")),
new JwtClaimValidator<String>("typ", "at+jwt"::equals)));
return decoder;
}
The wiring of that decoder into a filter chain is covered in Spring Security basics; the point here is that the algorithm list, the issuer, the audience and the clock skew are all explicit rather than defaulted.
Validating the claims
A verified signature is the beginning of the checklist, not the end.
| Claim | Rule |
|---|---|
iss | Exact string match against the expected issuer; no prefix or suffix matching |
aud | Must contain this API's identifier — this is what stops a token minted for another service |
exp | Reject expired tokens; allow at most 30–60 seconds of clock skew |
nbf | Reject tokens not yet valid, with the same skew allowance |
iat | Useful for rejecting implausibly old tokens and for freshness policies |
sub | The principal; combine with iss before using it as a local key |
scope | Enforce for the endpoint being called |
jti | Needed if you implement one-time use or a deny list |
Reject missing claims rather than defaulting them. A validator that treats an absent exp as "no expiry" turns one leaked token into a permanent credential. Run every check before any business logic touches the request, and return 401 with a WWW-Authenticate: Bearer error="invalid_token" header as RFC 6750 specifies, keeping the reason vague to the caller and precise in your logs.
Stateless tokens and the revocation problem
The property that makes self-contained tokens attractive — any service can validate one without asking the issuer — is exactly the property that makes revocation hard. Until it expires, a valid token stays valid, even if the account was disabled a minute ago. Four workable answers, usually combined:
- Short lifetimes. Five to fifteen minutes for an access token bounds the exposure and is the cheapest mitigation. Pair it with refresh-token rotation so the user experience stays smooth.
- A deny list. Store the
jtiof revoked tokens until theirexpand check it on each request. This is small and bounded, since entries expire on their own, but reintroduces a shared lookup. - A token version claim. Keep an integer per user, include it in issued tokens, and compare it against a cached value. Incrementing it invalidates everything issued for that user in one write — ideal for "log out everywhere" and for password changes.
- Introspection. Ask the authorization server on each call, optionally caching for a few seconds. Accurate, at the cost of a dependency in the hot path; an API gateway is a sensible place to do it once for many services.
Sensitive operations deserve stronger treatment regardless: re-authenticate, check auth_time, or require a proof-of-possession token before a transfer or a permission change.
Bearer tokens, storage and transport
A bearer token is a bearer instrument: whoever holds it can use it. That single sentence dictates most of the operational rules. Send it only over TLS 1.3 (or 1.2 with modern ciphers), only in the Authorization header — never in a query string, where it lands in access logs, proxy caches and Referer headers — and never log it, not even truncated in a debug build.
For browser clients the storage question has no free answer:
| Location | Exposure | Notes |
|---|---|---|
localStorage | Any script on the page reads it | One XSS flaw equals full token theft; persists across tabs and restarts |
| In-memory variable | Script on the page, while loaded | Lost on refresh; better than persistence, still XSS-reachable |
HttpOnly cookie | Not readable by script | Sent automatically, so CSRF defences are required |
| Backend-for-frontend | Not in the browser at all | Tokens stay server-side; the browser holds a session cookie |
The backend-for-frontend pattern — a small server-side component that performs the code exchange, keeps the tokens and proxies API calls — is the recommendation for new browser applications. Where the token must live in the browser, keep it in memory, keep it short-lived and treat cross-site scripting as a critical severity, because with a token in the page it is one.
Sender-constrained tokens remove the bearer problem altogether. DPoP (RFC 9449) has the client generate a key pair and send a signed proof header alongside each request; the token carries a thumbprint of the public key, so a stolen token without the private key is useless. Mutual-TLS certificate binding (RFC 8705) achieves the same for server-side clients. Both are worth the effort for high-value APIs.
GET /accounts/1042/transactions HTTP/1.1
Host: api.example.com
Authorization: DPoP eyJhbGciOiJFUzI1NiIsInR5cCI6ImF0K2p3dCJ9...
DPoP: eyJ0eXAiOiJkcG9wK2p3dCIsImFsZyI6IkVTMjU2Iiwiandr...
What the token does not do
Authentication tells you who is calling. Everything that follows is still your responsibility, and it is where most API breaches actually happen.
Scope is not authorization. A token with orders.read says the client may attempt to read orders. Whether this subject may read order 1042 is a question only your domain can answer, and forgetting to ask it is broken object-level authorization — the most common serious API flaw. Never derive ownership from an identifier in the path or body; derive it from sub and check.
@GetMapping("/orders/{id}")
@PreAuthorize("hasAuthority('SCOPE_orders.read')")
public OrderView get(@PathVariable long id, @AuthenticationPrincipal Jwt jwt) {
Order order = orders.findById(id).orElseThrow(NotFoundException::new);
if (!order.customerId().equals(jwt.getSubject())) {
throw new NotFoundException(); // 404, not 403 — do not confirm the record exists
}
return OrderView.of(order);
}
Validate every input. Types, ranges, lengths, enumerations and formats, on the server, rejecting rather than sanitising where possible. Cap request body size and collection lengths so a single call cannot exhaust memory, and put limits on any parser you expose.
Rate limit per identity, not only per address. Limits keyed on the subject or client identifier survive shared proxies and mobile networks; per-endpoint limits protect expensive operations; a global cap protects the service. Return 429 with Retry-After.
Do not leak through errors or shape. A stack trace, a distinct message for "no such user" versus "wrong password", or a 403 where a 404 would reveal less all hand information to an attacker. The status-code choices that follow from this are discussed alongside general REST API design.
Restrict CORS deliberately. Reflecting the Origin header and allowing credentials is equivalent to no policy at all; enumerate the origins you actually serve.
Log the decisions, not the tokens. Record subject, client, endpoint, outcome and correlation identifier. That trail is what makes an incident reconstructable, and it costs nothing at request time.
Key takeaways
- A signed JWT is readable by anyone holding it; signing gives integrity and origin, not confidentiality.
- Fix the accepted algorithms in code and select keys by
kidfrom a cached JWKS — never fromalg,jkuorjwkin the token. - Prefer asymmetric signatures so a resource server can verify without being able to mint tokens.
- Validate
iss,aud,expandnbfexplicitly and reject missing claims instead of defaulting them. - Stateless tokens cannot be recalled: use short lifetimes plus a deny list, a token-version claim or introspection where immediate revocation matters.
- Keep browser tokens out of persistent storage — prefer a backend-for-frontend — and consider DPoP or mTLS binding for high-value APIs.
- Scopes never replace resource-level authorization, input validation, rate limiting and careful error responses.
Sources and further reading
Frequently asked questions
- Is a JWT encrypted?
- A signed JWT is not. The header and payload are base64url-encoded, which is an encoding, not encryption, and anyone holding the token can read every claim. Signing guarantees integrity and origin, nothing more. If a claim must stay confidential from the client or from intermediaries, either leave it out of the token entirely or use JWE, which encrypts the payload.
- How do I revoke a JWT before it expires?
- You cannot revoke the token itself, because verification is offline by design. The practical approaches are short lifetimes so the window is small, a deny list of token identifiers consulted on each request, a per-user token version compared against a claim, or introspection against the issuer. Most systems combine short access tokens with revocation of the refresh token.
- Should the token go in localStorage or a cookie?
- Neither is unconditionally right. localStorage is readable by any script, so a single cross-site scripting flaw exfiltrates the token. A cookie can be HttpOnly and invisible to scripts, but it is sent automatically, which reintroduces cross-site request forgery unless you set SameSite and use a token pattern. The strongest option is a backend-for-frontend holding tokens server-side and giving the browser a session cookie.
- Why is the symmetric HS256 algorithm risky for a public API?
- It uses one shared secret for both signing and verification, so every service able to verify a token can also mint one. In a system with several resource servers that turns any compromised or careless service into a token factory. Asymmetric signing with RS256 or ES256 gives verifiers only the public key, so a compromised resource server cannot forge tokens for its peers.