What is JWT and how does it work?
json Web Token (JWT) is a compact, url-safe way to represent claims between two parties. A typical JWT has three base64url-encoded parts separated by dots: a header that states the algorithm, a payload containing claims (for example user ID, roles, expiry), and a signature that proves the token was issued by a trusted party. When a client presents a JWT to a server, the server verifies the signature, checks standard claims like expiration (exp), audience (aud), and issuer (iss), and then accepts or rejects the request. Because the token carries information inside it, many systems use JWT to avoid hitting a database for every request.
Why developers choose JWT
JWT feels attractive for a few reasons: it is stateless (the server doesn’t have to keep a session store for every client), it works well across domains and services because it is self-contained, and it integrates easily with modern single-page apps and APIs. If you have a microservices architecture, a signed JWT allows each service to validate the caller without central session lookup. The token format is standardized and supported by many libraries, which shortens development time for common authentication and authorization tasks.
Limitations and risks of JWT
Despite its advantages, JWT has some trade-offs that beginners must understand. Because a JWT is usually stateless, it is harder to revoke instantly,once issued, it remains valid until expiry unless you implement extra mechanisms. JWTs can be larger than opaque tokens when you store many claims, which increases bandwidth and cookie size. If you put sensitive data in the payload, anyone who intercepts the token and decodes it can read that data (signatures do not provide confidentiality). Implementation mistakes, such as accepting unsigned tokens or using weak algorithms, have led to notable security incidents in the past.
Common alternatives to JWT
Several alternatives are used depending on requirements: server-side sessions, opaque tokens, OAuth2 with access/refresh tokens, OpenID Connect, SAML for enterprise single sign-on, newer token types like PASETO, macaroons for constrained delegation, and simple API keys. Each option solves some of JWT’s shortcomings or fits specific environments better. Below are brief descriptions of the most relevant choices and why you might pick them.
Server-side sessions (traditional cookies)
Server-side sessions store authentication state on the server (in memory, database, or cache) and set a cookie with a session ID in the browser. This approach gives you easy revocation and immediate logout: destroying the server-side session invalidates the client instantly. For many web apps, especially those with tight security needs and server-rendered pages, sessions are simpler and safer to implement than JWT because the server retains full control over active sessions and can limit resources, detect anomalies, and rotate session IDs.
Opaque tokens
Opaque tokens are random identifiers issued by an authorization server and stored in a central store. They don’t reveal information when inspected,the server must look them up to obtain associated claims. This makes revocation straightforward and eliminates the risk of exposing claim contents. Opaque tokens pair well with OAuth2 access tokens when you want short-lived tokens that are easy to revoke and manage centrally.
OAuth2 and OpenID Connect
OAuth2 is an authorization framework; OpenID Connect (OIDC) adds authentication on top of OAuth2. These are not direct replacements for JWT, but they define flows and token types (often JWT access and ID tokens). OAuth2/OIDC provide standards for delegating access, obtaining consent, and using refresh tokens to maintain sessions without re-authentication. If you need third-party sign-in, federated identity, or well-defined flows across many clients (web, mobile, server), OAuth2 and OIDC are the right fit.
SAML
Security Assertion Markup Language (SAML) is an older XML-based protocol widely used by enterprises for single sign-on between identity providers and service providers. SAML is heavier than JWT and typically used in corporate environments where the identity provider and service provider are built to support it. Use SAML when integrating with enterprise identity systems that require it.
PASETO and other modern tokens
PASETO (Platform-Agnostic SEcurity TOkens) is a newer token standard designed to avoid common JWT pitfalls. It avoids algorithm flexibility that led to vulnerabilities in some JWT implementations and offers clearer defaults for encryption and signing. If you like the concept of self-contained, signed tokens but want a safer standard out of the box, PASETO is worth evaluating.
Macaroons and capability tokens
Macaroons are tokens that include caveats , restrictive conditions that can be added and delegated while preserving validity. They are useful when you need flexible delegation (for example, let a service issue a limited capability token to another system) while keeping verification efficient. This makes macaroons a good fit for fine-grained authorization scenarios where traditional JWT claims are too coarse.
API keys
API keys are simple secrets tied to a client or project. They are easy to use for server-to-server or service-to-service requests where identifying a caller is all that’s needed. API keys lack built-in expiration or fine-grained claims, so they are best for lower-risk interactions or when combined with additional checks and monitoring.
When to choose JWT and when to pick an alternative
If your app needs stateless authentication across distributed services and you can accept short-lived tokens or implement refresh token strategies, JWT is a reasonable choice because it reduces central lookups and integrates well with APIs and SPAs. Choose server-side sessions if you prioritize immediate revocation, simpler implementation for traditional web apps, or stronger server control over session data. Pick opaque tokens when you want revocation and privacy for token contents, and use OAuth2/OIDC for delegated access and federated login. Enterprise SSO commonly uses SAML. Consider PASETO if you want a token format that avoids common JWT pitfalls. The right choice depends on trade-offs among scalability, revocation, token size, inspectability, and ecosystem expectations.
Practical security and design recommendations
Whatever token approach you adopt, some practices reduce risk. Always use https to protect tokens in transit. Keep token lifetimes as short as practical and use refresh tokens with rotation where long sessions are required. Store tokens in secure locations: prefer HTTP-only, Secure cookies for browsers to reduce XSS risk, and use secure storage on mobile devices. Validate all claims strictly: check signature, issuer, audience, and expiration. Avoid embedding secrets or excessive personal data inside tokens. Implement token revocation lists or sliding windows when immediate revocation is required, and monitor usage to detect anomalies. Finally, use well-maintained libraries for token creation and verification to avoid common implementation errors.
Summary
JWT offers a convenient, stateless way to carry identity and authorization claims, which suits modern APIs and distributed systems, but it has downsides like harder revocation, larger token sizes, and potential misuse. Alternatives such as server-side sessions, opaque tokens, OAuth2/OIDC, SAML, PASETO, macaroons, and API keys each solve different problems and fit different environments. Choose based on your needs for revocation, cross-service validation, privacy of claims, and integration with third-party identity systems, and apply security best practices regardless of the token technology.
FAQs
1. Is a JWT secure enough for my application?
JWT can be secure if you follow best practices: use HTTPS, short expirations, proper signature validation, and secure storage for tokens. Avoid putting secrets in the payload and use well-maintained libraries. For scenarios needing instant revocation or very sensitive data, consider server-side sessions or opaque tokens instead.
2. How do I revoke a JWT before it expires?
Because JWTs are often stateless, common revocation options include keeping a server-side blacklist/denylist of token IDs, using short-lived access tokens with refresh tokens that can be revoked, or issuing tokens with a versioned claim (user token version) that the server checks against a central store. Each approach adds state or complexity but enables practical revocation.
3. When should I use OAuth2 or OpenID Connect instead of plain JWT?
Use OAuth2/OIDC when you need delegated authorization, third-party sign-in, or standardized flows across multiple client types (web, mobile, server). JWT is often used inside these frameworks as the token format, but OAuth2/OIDC provides the rules for issuance, consent, refresh flows, and scopes that a simple JWT-based system lacks.
4. What is PASETO and should I switch to it?
PASETO is a modern token standard designed to avoid common JWT pitfalls by removing algorithm negotiation and offering strong defaults for signing and encryption. If you want a safer token format and are building a greenfield project, PASETO is worth evaluating. migration requires changes in libraries and possibly token handling, so weigh benefits versus migration cost.



