JWT Security Best Practices for SaaS: Attacks, Token Rotation, and Safe Storage
JWT security best practices for SaaS: prevent alg:none attacks, implement refresh token rotation with reuse detection, and choose safe token storage.
JSON Web Tokens are the default session mechanism in almost every modern SaaS — and JWT security is poorly understood by most teams implementing it. The vulnerabilities are not theoretical: the alg:none attack bypasses signature verification entirely, algorithm confusion exploits let an attacker forge tokens using the server's public RSA key as an HMAC secret, and tokens stored in localStorage are stolen by any XSS on the page. Getting JWT security right is not about adding complexity — it is about avoiding a small set of well-documented implementation mistakes that consistently appear in real audits.
This guide covers the full production checklist for JWT security in a SaaS context: library configuration to block known attacks, access token lifetime, refresh token rotation, storage decisions, JWKS key rotation, multi-tenant claim isolation, and revocation. For the complementary topic of session escalation after the second factor passes, see the guide to TOTP two-factor authentication in Next.js SaaS.
The alg:none and Algorithm Confusion Attacks: Why Token Verification Is the First Failure Point
The two most exploited JWT vulnerabilities — alg:none and algorithm confusion — both originate in the same root cause: trusting the algorithm field in the token's own header rather than pinning it on the server. A token is a string the client sends to the server; the client can modify it. Any verifier that reads the alg field from the incoming token and uses it to choose the verification algorithm is operating on attacker-controlled input.
- →The alg:none attack: an attacker takes a valid token, modifies the payload claims — for example, sets admin to true or changes sub to another user's ID — sets alg to none in the header, removes the signature segment, and submits the modified token. A vulnerable verifier reads alg:none, skips signature verification, and accepts the forged token as valid. The fix is to pass a list of acceptable algorithms to your JWT library — for example, algorithms: ['RS256'] — and never derive the algorithm from the token header. A string check for the literal word 'none' is insufficient; the attack works with variants like nOnE and NONE with different capitalizations, so an allowlist is required.
- →Algorithm confusion (RS256 to HS256): when a server uses RS256 (asymmetric), it signs tokens with a private key and verifies with a public key. The public key is — as the name implies — public. If a verifier trusts the token header and falls back to HS256 when that value appears, an attacker can sign a forged token using the server's public key as the HMAC secret. The resulting signature is valid under HS256. The fix is identical: pin the allowed algorithm, never read it from the token.
- →Library-specific risks: jsonwebtoken in Node.js is safe when you pass the algorithms option to verify(). Without it, older versions accept any algorithm including none. The jose library — the recommended modern alternative — requires the algorithm at initialization and throws if the token header does not match. If you have custom JWT parsing code that calls verify without an algorithm constraint, treat it as a critical vulnerability.
- →Claim validation: algorithm pinning stops the two most common attacks, but the verifier must also validate exp (expiration), iat (issued at), iss (issuer), and aud (audience). An expired token that passes signature verification is still a valid attack vector if exp is not checked. These checks are built into every mature JWT library but can be disabled through configuration — confirm they are not.
Access Token Lifetime: Why 15 Minutes Is the Right Default
The access token lifetime is the window an attacker has to use a stolen token before it expires. A 24-hour access token means that any leak — from a log file, a misconfigured proxy, an XSS payload, or a compromised third-party service — gives the attacker a full day of access with no way to revoke it short of invalidating the user's session and forcing re-authentication. A 15-minute token limits that window to 15 minutes.
- →15 minutes is the consensus default for access token lifetime in production SaaS. It is short enough to limit breach exposure and long enough that a user does not experience token expiration during normal browsing. The access token is refreshed silently in the background using a refresh token — the user never sees an interruption.
- →1-hour tokens are acceptable for internal tooling or admin dashboards where re-authentication is tolerable. Anything longer than 24 hours for an access token is a design smell — the most common reason teams set long lifetimes is that they have not implemented a refresh flow, which is a gap worth fixing rather than papering over with long expiry.
- →Single-page applications running entirely in the browser are the highest-risk context for token storage. The access token should live in memory and disappear on page refresh, forcing the app to silently re-authenticate using the refresh token on each load. This is the intended pattern for SPAs that handle tokens correctly. Putting the access token in localStorage to survive a page refresh removes the expiry benefit and stores the token where XSS can read it.
- →Serverless and edge functions that forward the access token to downstream services need to validate exp server-side before forwarding. Do not assume a token is fresh because it was valid when the request started — a token cached in environment state may outlive its expiry if the function instance is reused across invocations.
Refresh Token Rotation with Reuse Detection
Refresh token rotation is the mechanism that lets short-lived access tokens coexist with long user sessions. When the access token expires, the client exchanges a refresh token for a new access token and a new refresh token. The old refresh token is immediately invalidated. If the same refresh token is used twice — reuse detection — that signals a stolen token being replayed, and the entire session should be revoked.
- →Rotation implementation: on each refresh, generate a new access token and a new refresh token, persist the new refresh token hash in the database, and invalidate the previous one atomically. The sequence must be a single database transaction or a compare-and-swap operation to prevent race conditions where two simultaneous refresh requests both succeed.
- →Reuse detection: before issuing a new pair, look up the submitted refresh token in the database. If the token exists but is already marked as used, that is a replay — revoke the entire family of tokens for that session and force re-authentication. This catches token theft even when the attacker rotates before the legitimate client does.
- →Token families: group refresh tokens issued from a single login into a family. If any member of the family triggers reuse detection, revoke the entire family. This prevents an attacker who stole one rotation cycle's token from staying alive indefinitely by continuing to rotate.
- →Absolute session lifetime: without an absolute cap, a user who refreshes once a day will stay authenticated forever. Set a maximum session duration — 7 or 30 days is common for SaaS — and require re-authentication after that point regardless of recent activity. Store session creation time in the token claims or in the refresh token record and enforce it server-side.
- →Opaque vs. JWT refresh tokens: refresh tokens should be opaque random strings, not JWTs. A JWT refresh token cannot be revoked without a denylist — which eliminates the stateless advantage — and a leaked JWT refresh token is immediately usable by an attacker without any server call. Store a hash of the opaque token server-side and issue the raw token to the client.
JWT Storage Security: HttpOnly Cookies vs. localStorage
The choice of where to store tokens in the browser is not a preference — it is a security boundary decision with concrete attack implications. The two options have different risk profiles, and the right choice depends on the attack surface you are most concerned about. For a full treatment of session-related account takeover vectors, see account takeover prevention in multi-tenant SaaS.
- →localStorage and sessionStorage are readable by any JavaScript running on the page. A single XSS vulnerability — a reflected injection, a compromised third-party script, a prototype pollution gadget — exposes every token stored there to exfiltration. The attacker's script does not need special privileges; document.cookie is not accessible to JavaScript but localStorage is fully readable. Storing access tokens in localStorage is not recommended for any SaaS handling sensitive user data.
- →HttpOnly, Secure, SameSite=Strict cookies are the recommended storage for both access tokens and refresh tokens in browser-based SaaS. HttpOnly means the cookie is not accessible to JavaScript, so XSS cannot read it. Secure restricts the cookie to HTTPS. SameSite=Strict prevents the cookie from being sent on cross-site requests, which blocks CSRF for state-modifying operations.
- →CSRF with SameSite cookies: SameSite=Strict prevents most CSRF by not sending the cookie on cross-site navigations. For APIs that also serve non-browser clients, adding a CSRF token header requirement — the double-submit cookie pattern or synchronizer token — provides defense in depth. Next.js App Router's server actions require a matching origin header by default in Next.js 15.2+, which provides this check for action-based mutation endpoints.
- →Memory storage for SPAs: a valid alternative is storing the access token in a module-level variable in a JavaScript module — effectively in-memory, not in a Web Storage API. It is inaccessible to other scripts and disappears on page refresh. The app re-authenticates silently using a rotation of HttpOnly refresh token cookie on each page load. This is the pattern Auth.js (NextAuth v5) uses by default and it is correct.
JWKS Endpoints and Signing Key Rotation Without Downtime
RS256 and ES256 (asymmetric algorithms) sign tokens with a private key and allow any service to verify them using the corresponding public key published at a JSON Web Key Set (JWKS) endpoint. Key rotation — periodically replacing the signing key pair — is a security hygiene requirement that limits exposure if the private key is ever leaked and is often required by SOC 2 and ISO 27001 controls.
- →Every JWT should include a kid (key ID) header field that identifies which key was used to sign it. The verifier reads the kid, fetches the matching key from the JWKS endpoint, and verifies the signature against that specific key. This allows multiple active keys at once, which is what enables zero-downtime rotation.
- →Rotation procedure: generate the new key pair, add the new public key to the JWKS endpoint alongside the old one using a different kid value, start signing new tokens with the new private key, wait for all tokens signed with the old key to expire — one access token lifetime — then remove the old public key. At no point do verifiers see a token they cannot validate.
- →Cache the JWKS response with a short TTL — 5 to 10 minutes — but implement a cache miss on unknown kid values. If a verifier receives a token with a kid it does not recognize, it should refresh the JWKS cache immediately before rejecting the token. This handles the case where tokens signed with the new key arrive at a verifier before its cache refreshes.
- →Store private keys in a secrets manager — AWS Secrets Manager, HashiCorp Vault, or Doppler — not in environment variables or configuration files. Environment variables in serverless functions may be logged, included in stack traces, or exposed via misconfigured introspection endpoints. The private key is the highest-value secret in your authentication stack.
Embedding Tenant Claims Safely in Multi-Tenant SaaS
In a multi-tenant SaaS, JWT claims must include the tenant identifier, and that identifier must be validated on every request against the data being accessed. The most common multi-tenant token vulnerability is not a JWT-specific attack — it is a failure to enforce the tenant boundary: a user from Tenant A presents a valid JWT and accesses Tenant B's data because the application trusts the user's session scope rather than checking the resource's tenant ownership. For a complete treatment of role-based access control within a tenant, see RBAC implementation in multi-tenant SaaS.
- →Include org_id (or tenant_id) as a claim in the access token, set at login based on the authenticated user's membership. Never derive the tenant from a request parameter, URL path segment, or header that the client controls — always read it from the validated token claims.
- →On every data access, join the resource's tenant ID against the token's org_id claim server-side. A query that fetches a record by ID alone without filtering by org_id is a horizontal privilege escalation vulnerability — the first user to guess or enumerate the record ID can access any tenant's data.
- →Avoid embedding mutable claims directly in the token — a user's role or permissions, for example, can change between token issuance and token use. If a user is demoted from admin while holding a 15-minute access token, they remain admin for up to 15 minutes. For high-privilege operations, verify the current state of the claim against the database rather than relying solely on the token payload.
- →Service-to-service tokens in a multi-tenant system should include the tenant context explicitly and should be scoped to the minimum set of operations the calling service needs. A backend microservice token that is not tenant-scoped can access all tenants' data if the downstream service does not enforce boundaries independently. Treat inter-service JWTs with the same scrutiny as user-facing ones.
Revoking JWTs: Logout, Compromise Response, and Session Invalidation
The stateless property of JWTs — no server lookup required for verification — is their performance advantage and their revocation problem. A signed JWT is valid until it expires. If a user logs out, changes their password, or reports account compromise, the access token they hold continues to verify successfully until its exp claim passes. Handling this correctly requires a targeted denylist rather than abandoning the stateless model entirely.
- →Denylist access tokens on logout and compromise events. Store the token's jti (JWT ID) claim — a unique identifier every token should include — in a Redis set with a TTL matching the token's remaining lifetime. The verifier checks the denylist after signature validation. The denylist entry expires automatically, keeping the set bounded. This adds one Redis read per request but avoids a full database lookup on the hot path.
- →Revoke refresh tokens server-side on logout, password change, 2FA disable, and account compromise. The refresh token record in the database should be marked as revoked. On the next attempted refresh, the server checks the record, finds it revoked, and rejects the request. This is the more important revocation to get right: a revoked access token is dangerous for 15 minutes; a live refresh token keeps the session open indefinitely.
- →Password changes and 2FA changes should invalidate all existing sessions, not just the current one. Store a password_changed_at or mfa_changed_at timestamp on the user record and include the user's security version — a hash or incrementing counter — in the access token claims. On each request, compare the token's security version against the current database value. A mismatch forces re-authentication.
- →Audit log every revocation event: the reason (logout, password change, admin action, security incident), the user ID, the session ID, and the timestamp. This record is what you present during a SOC 2 audit or a security incident review. Without it, you cannot reconstruct when access was revoked in response to a reported compromise.
Frequently Asked Questions
What is the alg:none attack in JWT?
The alg:none attack exploits JWT libraries that read the algorithm to use for signature verification from the token's own header. An attacker modifies the token payload, sets the alg field to none, removes the signature segment, and submits the modified token. A vulnerable verifier reads alg:none, skips verification, and accepts the forged token as valid. The defense is to pass an explicit allowlist of accepted algorithms to your JWT library's verify function and never trust the algorithm value from the token header.
Should I store JWTs in localStorage or HttpOnly cookies?
HttpOnly, Secure, SameSite=Strict cookies are the correct choice for production SaaS. localStorage is readable by any JavaScript on the page, which means a single XSS vulnerability — including a compromised third-party analytics or chat widget script — can exfiltrate the token. HttpOnly cookies are not accessible to JavaScript at all. The tradeoff is that cookies require CSRF protection, which SameSite=Strict handles for most cases and a double-submit header check covers for edge cases.
How do I implement refresh token rotation?
On each access token refresh, issue a new access token and a new refresh token, invalidate the old refresh token in the database, and return the new pair. Use an opaque random string as the refresh token (not a JWT). Store a hash of the token server-side. If the same refresh token is submitted twice, that is reuse detection: revoke all tokens in the session family and require re-authentication. This detects theft even when the attacker refreshes before the legitimate client.
How often should I rotate JWT signing keys?
A 90-day rotation cycle is a common baseline for RS256 or ES256 signing keys, and many compliance frameworks require at least annual rotation. The procedure is: generate the new key pair, publish the new public key at the JWKS endpoint alongside the old one using a different kid value, start signing new tokens with the new key, wait one access token lifetime for old tokens to expire, then remove the old public key. This zero-downtime procedure requires that every JWT includes a kid header and that verifiers implement cache-miss-on-unknown-kid.
Can JWTs be revoked before they expire?
Yes, but it requires a server-side check. The simplest approach is a jti-based denylist in Redis: on logout or account compromise, write the token's jti to a Redis set with a TTL equal to the token's remaining lifetime. Each verifier checks the denylist after signature validation. This keeps the access token denylist bounded and auto-expiring. For refresh tokens, the revocation record lives in the primary database rather than Redis, since refresh tokens have longer lifetimes and warrant durable storage.
How Belsoft Helps Secure Your SaaS Authentication
JWT misconfiguration is one of the most consistent findings in a Belsoft security audit. The specific issues — algorithm pinning absent, long-lived access tokens, tokens in localStorage, missing jti claims, tenant boundaries not enforced in data queries — appear in auth code written by experienced teams, not just vibe-coded apps, because JWT security requires implementing a set of non-obvious constraints that most tutorials skip. The Belsoft security audit reviews your token issuance, storage, rotation, and revocation logic by hand, then helps your team fix what it finds and retests to verify the fixes held.
For teams that want an automated baseline first, DeployReady runs 30+ static checks including exposed secrets, missing security headers, and common auth misconfigurations — it is free on npm and runs locally in under a minute. The manual audit layer catches what static analysis misses: logic errors, tenant isolation failures, and the specific JWT vulnerabilities that require understanding your token flow to find.
“A JWT that verifies is not the same as a JWT that is secure. The gap between the two is where most SaaS auth breaches happen.”
Written by
Marco Silva
Security Engineer, Belsoft Solutions
More from the blog
Ready to partner?
Let's talk about your company.
30 minutes. No pitch. We talk through how you run today and where AI and automation would help.
Book a free audit
