JWT (JSON Web Token)

Categories:

A user logs into a mobile banking app in Sydney, makes a transaction, checks their balance, then closes the app. When they reopen it five minutes later, they're still authenticated without logging in again. Behind the scenes, a JWT stored on their device proves their identity to the server without the server needing to remember them between requests. JSON Web Tokens are a compact, URL-safe method of representing claims between two parties. They've become the standard authentication mechanism for modern web applications, mobile apps, and APIs because they eliminate the need for server-side session storage while maintaining security.

What Is a JWT?
Why Do Modern Applications Use JWTs?
What Are the Security Considerations?
How Do You Implement JWTs Properly?
Where Do JWTs Fit in Modern Architecture?

What Is a JWT?

A JSON Web Token is a string of encoded data split into three parts separated by periods: a header, a payload, and a signature. The header specifies the token type and signing algorithm. The payload contains claims, which are statements about the user and additional metadata like expiration time. The signature verifies that the token hasn't been tampered with, created by encoding the header and payload together with a secret key.

The token looks like random characters but it's actually base64-encoded JSON. Anyone can decode a JWT to read its contents, which is why you never store sensitive information like passwords in the payload. The security comes from the signature. Only someone with the secret key can create a valid signature, so while anyone can read the token, only the server can verify it's legitimate and issue new ones.

This structure enables stateless authentication. When a user logs in, the server creates a JWT containing their user ID and permissions, signs it with a secret key, and sends it to the client. For subsequent requests, the client includes this token in the authorization header. The server verifies the signature and extracts the user information from the payload without querying a database. This dramatically reduces server load and enables horizontal scaling since any server can verify any token without shared session storage.

Why Do Modern Applications Use JWTs?

Traditional session-based authentication requires the server to store session data for every logged-in user. When a request arrives, the server looks up the session ID in its database or memory cache to determine who the user is and what they're allowed to do. This creates several problems for modern applications. It requires shared state across servers, complicating horizontal scaling. It creates a single point of failure if the session store goes down. It adds latency to every request from database lookups.

JWTs solve these problems through statelessness. At The Digital Bunch, we implement JWT-based authentication for applications that need to scale efficiently. By switching from session-based authentication to JWTs, authentication layers become completely stateless. Any server can verify any request without coordination, enabling horizontal scaling by simply adding more application servers.

The approach also simplifies authentication across multiple services. In a microservices architecture, each service needs to verify user identity. With session-based authentication, every service would need access to the central session store. With JWTs, each service can independently verify tokens using the same secret key or public key, without any coordination or shared infrastructure.

JWTs enable single sign-on across different domains. A user logs into one application and receives a JWT. That token can be used to authenticate with entirely separate applications that trust the same issuer. This is how "Sign in with Google" and similar OAuth flows work. The identity provider issues a JWT, and multiple applications can accept it without implementing their own authentication systems.

What Are the Security Considerations?

JWTs solve certain problems elegantly but introduce their own security considerations. The most critical is that JWTs are typically stateless, meaning the server doesn't track which tokens are valid. Once issued, a JWT remains valid until it expires. If someone steals a token, they can impersonate that user until expiration. This is why short expiration times are standard practice, often 15 minutes to an hour for access tokens.

The solution is refresh tokens. Applications issue two tokens at login: a short-lived access token used for API requests, and a longer-lived refresh token stored securely that can generate new access tokens. When the access token expires, the client uses the refresh token to get a new one without requiring the user to log in again. The refresh token can be revoked server-side, providing a logout mechanism despite stateless access tokens.

Another consideration is JWT size. Unlike a simple session ID, a JWT contains actual data and can grow large if you include many claims. Large tokens increase bandwidth usage and can hit header size limits. We optimize by including only essential claims in access tokens, storing detailed permissions server-side and caching them, and using short claim names to reduce token size.

How Do You Implement JWTs Properly?

Implementation requires decisions about signing algorithms, token structure, storage location, and refresh mechanisms. For signing, HS256 uses a shared secret key and is simpler but requires every service to have the secret. RS256 uses public-key cryptography where the private key signs tokens and multiple services can verify using the public key without accessing the private key. We typically recommend RS256 for production systems, especially in microservices architectures.

For web applications, JWTs are typically stored in memory or httpOnly cookies. LocalStorage is convenient but vulnerable to XSS attacks. HttpOnly cookies prevent JavaScript access, improving security, though they require CSRF protection. Mobile applications store tokens in secure platform-specific storage like iOS Keychain or Android Keystore.

The token payload should include standard claims like issuer, subject (user ID), expiration time, and issued-at timestamp. Custom claims might include user roles, permissions, or account status. Keep the payload minimal since it travels with every request. Clients who initially included extensive user profile data in JWTs often create tokens over 2KB that cause performance issues. Trimming to essential claims and fetching additional data as needed resolves the problem.

Token refresh requires careful UX consideration. Users shouldn't notice when access tokens expire. Applications should detect expiring tokens proactively and refresh them in the background. Failed requests due to expired tokens should trigger automatic refresh and retry.

Where Do JWTs Fit in Modern Architecture?

JWTs have become the standard for API authentication, particularly for mobile applications, single-page applications, and microservices. They enable serverless architectures where stateless functions handle requests without persistent storage. They support OAuth and OpenID Connect flows that power third-party authentication. They allow edge computing where authentication verification happens at CDN nodes without backend requests.

The pattern has limitations. Stateless tokens can't be revoked immediately, making them unsuitable for high-security scenarios requiring instant session termination. Large-scale applications might need hybrid approaches where critical actions require additional verification beyond JWT authentication. But for most modern applications, JWTs provide the right balance of security, scalability, and developer experience. They've enabled the shift toward stateless, horizontally scalable architectures that power contemporary web and mobile applications.

Have Questions?

Need expert guidance on this? Let's talk. Our deep industry knowledge can transform your challenge into an opportunity.