JSON Web Tokens (JWT): A Complete Guide
What’s inside a JWT: header, payload, and signature, and how to inspect claims and expiry without verifying the secret.
JSON Web Tokens (JWT) are widely used for securing APIs and passing identity between services, including from single-page applications (SPAs). But what exactly is that long string of characters starting with eyJ?
Anatomy of a JWT
A JWT is composed of three parts, separated by dots (.):
- Header: Contains metadata about the token type and cryptographic algorithm.
- Payload: Contains the "claims" (user data like ID, role, expiration).
- Signature: A cryptographic signature to verify the token hasn't been tampered with.
1. The Header
{
"alg": "HS256",
"typ": "JWT"
}2. The Payload
{
"sub": "1234567890",
"name": "John Doe",
"iat": 1516239022
}Decoding vs. Verifying
It's crucial to understand that decoding a JWT is different from verifying it.
Since the header and payload are just Base64Url encoded, anyone can decode them and read the contents. This is why you should never put sensitive secrets (like passwords) inside a JWT payload.
Verifying, however, requires the right key: the shared secret for HMAC algorithms such as HS256, or the issuer's public key for RSA and ECDSA algorithms. The server uses it to check the signature against the header and payload it received.
Common Use Cases
- Authentication: The most common scenario. Once the user is logged in, each subsequent request will include the JWT, allowing the user to access routes, services, and resources.
- Information Exchange: A signed JWT lets the receiver check who issued it and that the contents were not altered in transit. The contents are still readable by anyone who holds the token.
Standard JWT Claims
JWTs can contain any claims you want, but there are standard registered claims (defined in the JWT specification):
| Claim | Description |
|---|---|
| iss | Issuer - who created the token |
| sub | Subject - the user ID or identifier |
| aud | Audience - who the token is intended for |
| exp | Expiration time (Unix timestamp) |
| iat | Issued at time (Unix timestamp) |
| nbf | Not before - token is invalid before this time |
| jti | JWT ID - a unique identifier for the token |
JWT Security Best Practices
- Use HTTPS: Always transmit JWTs over HTTPS to prevent man-in-the-middle attacks
- Set short expiration times: Use refresh tokens for long-lived sessions
- Validate all claims: Don't just check the signature - verify exp, nbf, aud, and iss
- Store securely: In browsers, prefer httpOnly cookies (with CSRF protection) over localStorage for sensitive tokens. See the storage trade-offs below.
- Use strong secrets: For HS256, use a long, random secret (RFC 7518 requires a key at least as large as the hash output, 256 bits). For RS256, use proper key management
- Never put secrets in the payload: Remember, the payload is easily decodable
Common JWT Vulnerabilities
Algorithm Confusion Attack
If a server accepts tokens with "alg": "none" or doesn't verify the algorithm, attackers can create tokens without a valid signature. Always verify the algorithm matches what you expect.
Weak Secrets
Using weak or predictable secrets makes it easy for attackers to forge tokens. Use cryptographically secure random secrets that are at least 256 bits long.
Token Replay
If a token is intercepted, it can be reused until it expires. Implement token revocation mechanisms or use short expiration times with refresh tokens.
JWT vs. Session Tokens
JWTs are stateless, meaning the server doesn't need to store session data. This makes them ideal for:
- Microservices architectures where services don't share session storage
- Single Page Applications (SPAs) that make API calls to multiple services
- Mobile applications that need to authenticate with backend APIs
However, traditional session tokens (stored server-side) are better when you need:
- Immediate revocation (JWTs can't be revoked until they expire)
- Strict security requirements (sessions can be invalidated instantly)
- Large payloads (JWTs should be kept small due to size constraints)
A Real Token, Decoded by Hand
JWTs are specified in RFC 7519, and the signed form is a JSON Web Signature (JWS, RFC 7515): BASE64URL(header) + "." + BASE64URL(payload) + "." + BASE64URL(signature). The signature is an HMAC-SHA256 over the first two segments joined by a dot. This token was generated with the secret my-secret and the header and payload shown above:
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.EpM5XBzTJZ4J8AfoJEcJrjth8pfH28LWdjLo90sYb9gThe reason JWT headers start with eyJ is that a JSON object opens with {" followed by a key that starts with a letter, and those first three bytes encode to eyJ in Base64 (for a header beginning with {"a, as in {"alg", the prefix is eyJh). Decoding the first two segments needs no key at all, only the Base64URL alphabet, which you can try in the JWT Decoder.
Verifying a Signature in Node.js
In production use a maintained library, but seeing the mechanics removes the mystery. This function pins the algorithm, recomputes the HMAC, compares in constant time and checks exp:
const { createHmac, timingSafeEqual } = require("crypto");
function verifyHS256(token, secret) {
const [h, p, s] = token.split(".");
const header = JSON.parse(Buffer.from(h, "base64url"));
if (header.alg !== "HS256") throw new Error("unexpected alg");
const expected = createHmac("sha256", secret).update(h + "." + p).digest();
const actual = Buffer.from(s, "base64url");
if (actual.length !== expected.length || !timingSafeEqual(actual, expected))
throw new Error("bad signature");
const claims = JSON.parse(Buffer.from(p, "base64url"));
if (claims.exp && claims.exp < Date.now() / 1000) throw new Error("expired");
return claims;
}Running it against the token above gives:
verifyHS256(token, "my-secret"); // { sub: '1234567890', name: 'John Doe', iat: 1516239022 }
verifyHS256(token, "wrong-secret"); // Error: bad signature
verifyHS256(noneToken, "my-secret"); // Error: unexpected algSigning Algorithms Compared
The algorithm names live in the JWS header and are defined in RFC 7518 (JSON Web Algorithms). The three you will meet most often:
| alg | Type | Key model |
|---|---|---|
| HS256 | HMAC with SHA-256 | One shared secret signs and verifies |
| RS256 | RSA PKCS#1 v1.5 with SHA-256 | Private key signs, public key verifies |
| ES256 | ECDSA with P-256 and SHA-256 | Private key signs, public key verifies |
Choose HS256 when one service both issues and verifies tokens. Choose an asymmetric algorithm when many services (or third parties) need to verify tokens but must not be able to mint them: they only get the public key, often published as a JWKS endpoint.
alg=none and Algorithm Confusion in Detail
The spec defines "unsecured" JWTs with "alg": "none" and an empty signature. Here is one carrying the same payload as above, just the header and payload with a trailing dot:
eyJhbGciOiJub25lIiwidHlwIjoiSldUIn0.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.A verifier that trusts the token's own header to pick the algorithm will accept this with no secret at all. The related algorithm confusion attack targets servers that verify RS256 tokens: the attacker changes the header to HS256 and signs with the server's public key (which is not secret) as the HMAC key. If the library uses the same key material for whichever algorithm the header names, the forged signature validates.
The defence is the same in both cases: configure the expected algorithm list on the server and never derive it from the token. RFC 8725 (JWT Best Current Practices) recommends exactly this, along with validating iss and aud.
Time Claims: Units, Clock Skew and Debugging
exp, nbf and iat are NumericDate values: seconds since 1970-01-01T00:00:00Z, not milliseconds. The iat in our sample, 1516239022, is 2018-01-18T01:30:22Z. Passing Date.now() (milliseconds) straight into exp produces a token that appears to expire tens of thousands of years from now.
- "Token expired" right after login: compare server clocks. A few seconds of drift can break
nbfandiatchecks, so most libraries offer a small leeway setting. - Wrong
audoriss: tokens from a staging identity provider reaching a production API are a common cause of unexplained 401 responses. - Converting values: paste any claim into the Timestamp Converter to read it as a date.
Storage and Revocation Trade-offs
A stateless token cannot be recalled before exp unless the server remembers something, and that is the central design trade-off. Common patterns:
- Short-lived access token plus refresh token: the access token lives minutes, while the refresh token is stored server-side and can be revoked.
- Denylist by
jti: store the IDs of revoked tokens until they would have expired anyway. This reintroduces state, but only for a small set. - Browser storage:
localStorageis readable by any script on the page, so an XSS bug exposes the token. AnHttpOnlycookie hides it from scripts but needs CSRF protection (for exampleSameSitecookies or anti-CSRF tokens).
Also remember the size cost: the token travels on every request, and Base64URL adds about a third to the JSON. Keep claims minimal and look up the rest server-side. If a request is rejected for cross-origin reasons rather than auth, see CORS Explained.
Inspect Your Tokens
Debugging authentication issues often requires inspecting the claims inside your token. Is the exp (expiration) timestamp correct? Does the user have the admin role? Is the iss (issuer) what you expect?
Use our JWT Decoder to instantly parse and inspect your tokens client-side, without sending them to any server. This tool is perfect for:
- Debugging authentication issues in development
- Inspecting claims such as
iss,audandsubbefore making API calls - Understanding JWT structure and contents
- Reading
exp,iatandnbfvalues, which you can paste into the Timestamp Converter - Learning how JWTs work through hands-on exploration
All decoding happens in your browser, so the token is not sent to our server. The tool does not verify the signature, so a decoded token is not a trusted one.
Frequently Asked Questions
Is a JWT encrypted?
A standard signed JWT is not encrypted. Its payload is only Base64URL-encoded and readable by anyone holding the token. Encrypted tokens exist (JWE, RFC 7516) but are a separate format, and most "JWTs" in the wild are signed only.
Can I trust a token just because I decoded it?
No. Decoding only reads the claims, and an attacker can write any claims they like. Trust comes from verifying the signature with the right key and algorithm, then validating exp, iss and aud.
How do I log a user out if JWTs are stateless?
Delete the token on the client, revoke the refresh token on the server, and keep access token lifetimes short. For immediate invalidation, keep a denylist of jti values or switch to server-side sessions.
What is the difference between HS256 and RS256?
HS256 uses one shared secret for both signing and verifying, so every verifier could also forge tokens. RS256 uses a private key to sign and a public key to verify, so verifiers cannot mint tokens.
Written by Kashyap Thakar
Spotted a mistake? Let me know
Try these tools
Use these tools alongside this guide