Introduction
JWT stands for JSON Web Token. It is a compact, self-contained method of securely transmitting information between parties. A JWT is an encoded string that contains encoded data (claims) about a user and is cryptographically signed to prove it has not been tampered with. Instead of storing user sessions on the server, modern applications often use JWTs, which are stateless tokens that the server can verify without any database lookup.
What is JWT?
JWT stands for JSON Web Token. It is a compact, self-contained method of securely transmitting information between parties. A JWT is an encoded string that contains encoded data (claims) about a user and is cryptographically signed to prove it has not been tampered with. Instead of storing user sessions on the server, modern applications often use JWTs, which are stateless tokens that the server can verify without any database lookup.
Think of a JWT like a digital passport: it contains information about who you are, has been verified by an authority (the server), and can be checked whenever you use it without the authority needing to look up your information in a database.
The Three Parts of a JWT
Every JWT consists of three parts separated by dots: header, payload, and signature. Here is an example JWT:
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkFsaWNlIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c
Part 1: Header
The header contains metadata about the token, specifically the type (always JWT) and the algorithm used to sign it (like HS256 or RS256).
{
"alg": "HS256",
"typ": "JWT"
}
This is Base64-encoded to create the first part of the token. The algorithm specifies how the signature will be created.
Part 2: Payload (Claims)
The payload contains the actual data you want to transmit. These are called "claims." They typically include information about the user and metadata about the token itself.
{
"sub": "1234567890",
"name": "Alice",
"email": "alice@example.com",
"iat": 1516239022,
"exp": 1516325422
}
Common claims include: "sub" (subject, usually the user ID), "name" (user's name), "email" (email address), "iat" (issued at timestamp), and "exp" (expiration timestamp). The "exp" field is crucial—it specifies when the token expires and is no longer valid. This is also Base64-encoded to create the second part of the token.
Part 3: Signature
The signature is created by taking the header and payload, combining them, and cryptographically signing the result using a secret key and the algorithm specified in the header. This signature proves that the token has not been modified.
HMACSHA256(
base64UrlEncode(header) + "." + base64UrlEncode(payload),
secret
)
When the server receives a JWT, it verifies the signature by recalculating it using the same secret key. If the calculated signature matches the provided signature, the token is authentic. If someone modifies the payload or header, the signature will no longer match, and the token is rejected.
How JWT Authentication Works
Here is the typical flow of JWT-based authentication:
1. User logs in: The user provides their username and password to the login endpoint.
2. Server verifies credentials: The server checks the password against the stored hash in the database.
3. Server creates JWT: If credentials are correct, the server creates a JWT containing the user's ID and other relevant claims, signs it with a secret key, and sends it to the client.
4. Client stores JWT: The client stores the JWT (usually in localStorage, sessionStorage, or a secure cookie).
5. Client sends JWT with requests: For subsequent requests, the client includes the JWT in the Authorization header: Authorization: Bearer [JWT]
6. Server verifies JWT: The server receives the JWT, verifies the signature using its secret key, and checks if the token is expired. If valid, the server processes the request without needing a database lookup.
JWT vs Sessions: Key Differences
Sessions: The server stores session data (user ID, login time, permissions) in memory or a database. When a user logs in, the server creates a session ID, sends it to the client as a cookie, and the client includes the session ID in subsequent requests. The server looks up the session ID in its database to verify the user.
JWTs: The server signs user data into a token and sends it to the client. The client includes the JWT with requests, and the server verifies it using the signature. No database lookup is needed.
Scalability: Sessions require server-side storage, making them less suitable for distributed systems with multiple servers. JWTs are stateless, so any server in a load-balanced system can verify them without accessing a database.
Performance: JWTs reduce database queries (better performance), but sessions are better at enforcing immediate logout (you can delete the session record instantly, whereas invalidating a JWT is harder before expiration).
Security Best Practices for JWTs
1. Use HTTPS Only
Always transmit JWTs over HTTPS to prevent man-in-the-middle attacks. Sending JWTs over plain HTTP exposes them to interception.
2. Keep Your Secret Key Secure
Never expose your secret key in client-side code, version control, or anywhere publicly accessible. Store it in environment variables on your server.
3. Use Reasonable Expiration Times
Set the "exp" claim to a reasonable value (typically 15 minutes to 1 hour). Shorter expiration times reduce the impact of token theft. Use refresh tokens to get new access tokens without re-logging in.
4. Validate All Claims
When verifying a JWT, check not just the signature, but also the expiration time and any other relevant claims. Use the JWT Decoder tool to inspect tokens and verify their contents.
5. Use Strong Signing Algorithms
Prefer RS256 (RSA with SHA-256) over HS256 for production applications, as it uses asymmetric cryptography and is more secure for distributed systems.
Frequently Asked Questions
What is a JWT token?
A JWT (JSON Web Token) is a compact, self-contained token used for securely transmitting information between parties. It consists of three Base64-encoded parts — header, payload, and signature — separated by dots. JWTs carry user identity and claims within the token itself, eliminating the need for server-side session storage.
How does a JWT token work?
When a user logs in, the server creates a JWT containing user identity claims and signs it with a secret key. The client stores the token and sends it with every request in the Authorization header. The server verifies the signature and claims without needing a database lookup, making the process stateless and fast.
What are the three parts of a JWT token?
Every JWT has a header (metadata like the signing algorithm), a payload (claims about the user such as ID, name, and expiration), and a signature (cryptographic proof that the token has not been tampered with). Each part is separated by a dot character.
Is a JWT token secure?
JWT tokens are secure when implemented correctly. Always transmit them over HTTPS, keep secret keys secure on the server, set short expiration times, and validate all claims on every request. The payload is Base64-encoded (not encrypted), so never include sensitive data like passwords in the token.
What is the difference between a JWT and a session?
Session-based authentication stores user data on the server and sends a session ID cookie to the client. JWTs are stateless — the token itself contains all user information, so no server-side storage is needed. JWTs scale better across multiple servers but cannot be revoked as easily as sessions.
How long does a JWT token last?
JWT expiration is set by the exp claim in the payload. Access tokens typically last 15 minutes to 1 hour. Refresh tokens can last days or weeks. Setting short expiration times limits the damage if a token is stolen, while refresh tokens allow seamless re-authentication.
Where should I store a JWT token on the client?
The most secure approach is storing access tokens in memory and refresh tokens in HTTP-only cookies. localStorage and sessionStorage are simpler but vulnerable to XSS attacks. For sensitive applications, avoid storing tokens where JavaScript can access them directly.
Can I put sensitive data in a JWT payload?
No. The JWT payload is Base64-encoded, not encrypted. Anyone with the token can decode and read the payload contents. Never include passwords, credit card numbers, or other sensitive information in a JWT. Use it only for non-sensitive identity and authorization claims.
What is the difference between HS256 and RS256 signing?
HS256 uses a single shared secret key to both sign and verify tokens. RS256 uses asymmetric cryptography — a private key signs the token and a public key verifies it. RS256 is more secure for distributed systems because multiple services can verify tokens without sharing a secret key.
When should I use JWT tokens?
JWT tokens are ideal for single sign-on (SSO), mobile app authentication, API authentication, and microservices architectures. They work well wherever you need stateless, scalable authentication that crosses domain boundaries. For simple single-page applications with a single server, traditional sessions may be simpler.
Conclusion
JWT tokens are a modern, scalable approach to authentication that fits perfectly with distributed systems, microservices, and mobile applications. By encoding user information and signing it cryptographically, JWTs allow servers to verify user identity without session storage. While they require careful attention to security (using HTTPS, protecting secret keys, setting expiration times), they offer significant advantages in performance and scalability. Understanding how JWTs work is essential for any modern web developer.
Frequently asked questions
What is a JWT token?
A JWT (JSON Web Token) is a compact, self-contained token used for securely transmitting information between parties. It consists of three Base64-encoded parts — header, payload, and signature — separated by dots. JWTs carry user identity and claims within the token itself, eliminating the need for server-side session storage.
How does a JWT token work?
When a user logs in, the server creates a JWT containing user identity claims and signs it with a secret key. The client stores the token and sends it with every request in the Authorization header. The server verifies the signature and claims without needing a database lookup, making the process stateless and fast.
What are the three parts of a JWT token?
Every JWT has a header (metadata like the signing algorithm), a payload (claims about the user such as ID, name, and expiration), and a signature (cryptographic proof that the token has not been tampered with). Each part is separated by a dot character.
Is a JWT token secure?
JWT tokens are secure when implemented correctly. Always transmit them over HTTPS, keep secret keys secure on the server, set short expiration times, and validate all claims on every request. The payload is Base64-encoded (not encrypted), so never include sensitive data like passwords in the token.
What is the difference between a JWT and a session?
Session-based authentication stores user data on the server and sends a session ID cookie to the client. JWTs are stateless — the token itself contains all user information, so no server-side storage is needed. JWTs scale better across multiple servers but cannot be revoked as easily as sessions.
How long does a JWT token last?
JWT expiration is set by the exp claim in the payload. Access tokens typically last 15 minutes to 1 hour. Refresh tokens can last days or weeks. Setting short expiration times limits the damage if a token is stolen, while refresh tokens allow seamless re-authentication.
Where should I store a JWT token on the client?
The most secure approach is storing access tokens in memory and refresh tokens in HTTP-only cookies. localStorage and sessionStorage are simpler but vulnerable to XSS attacks. For sensitive applications, avoid storing tokens where JavaScript can access them directly.
Can I put sensitive data in a JWT payload?
No. The JWT payload is Base64-encoded, not encrypted. Anyone with the token can decode and read the payload contents. Never include passwords, credit card numbers, or other sensitive information in a JWT. Use it only for non-sensitive identity and authorization claims.
What is the difference between HS256 and RS256 signing?
HS256 uses a single shared secret key to both sign and verify tokens. RS256 uses asymmetric cryptography — a private key signs the token and a public key verifies it. RS256 is more secure for distributed systems because multiple services can verify tokens without sharing a secret key.
When should I use JWT tokens?
JWT tokens are ideal for single sign-on (SSO), mobile app authentication, API authentication, and microservices architectures. They work well wherever you need stateless, scalable authentication that crosses domain boundaries. For simple single-page applications with a single server, traditional sessions may be simpler.