Whenever you log into a modern web application, single-page app (SPA), or mobile app, the backend server rarely keeps a persistent session row in its database for every click you make. Instead, it issues a JSON Web Token (JWT).

Defined by RFC 7519, a JWT is an open, compact, URL-safe standard for securely transmitting information between two parties as a digitally signed JSON object. Because JWTs are stateless and self-contained, the server can verify who you are, what permissions you hold, and whether the token has expired—all without querying a central database session table.

However, despite their popularity in modern architectures, JSON Web Tokens are widely misunderstood. Many developers mistakenly treat JWTs as “encrypted” passwords, store sensitive credentials in payloads, or fall victim to critical token-storage vulnerabilities.

In this guide, you will learn the exact three-part anatomy of a JWT, inspect how cryptographic signatures prevent tampering, compare HS256 vs. RS256, and discover the golden rules of token security.


The Anatomy of a JWT: Three Parts Separated by Dots

A typical JWT looks like a long string of garbled alphanumeric characters:

eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c

Notice the two periods (.). A JWT is strictly composed of three distinct sections:

  1. Header (Red): The metadata defining the token type and cryptographic algorithm.
  2. Payload (Purple): The actual claims and user data.
  3. Signature (Blue): The cryptographic verification hash ensuring data integrity.
[  Header  ] . [  Payload  ] . [ Signature ]
 Base64URL       Base64URL       HMAC-SHA256
Diagram illustrating the 3-part structure of a JSON Web Token and the stateless client-server authentication pipeline
Figure 1: Anatomy of a JSON Web Token (Header, Payload, Signature) and the stateless authentication flow between client and backend.

You can inspect, decode, and verify any token client-side without sending tokens to third-party servers using the DwellixTools JWT Decoder & Inspector.


1. The Header: Algorithm & Token Type

The Header is a small JSON object specifying the cryptographic algorithm used to sign the token:

{
  "alg": "HS256",
  "typ": "JWT"
}
  • alg (Algorithm): The hashing or signing method. Common algorithms include HS256 (HMAC with SHA-256), RS256 (RSA signature with SHA-256), or ES256 (ECDSA with P-256 and SHA-256).
  • typ (Type): Almost always "JWT".

This JSON string is converted into URL-safe text using Base64URL encoding.


2. The Payload: Claims and User Identity

The Payload contains the claims—statements about an entity (typically the authenticated user) and additional operational metadata.

{
  "sub": "usr_94827104",
  "name": "Jane Doe",
  "role": "admin",
  "iat": 1732982400,
  "exp": 1732986000
}

Claims fall into three distinct categories:

A. Registered Claims (Predefined RFC 7519 Standards)

While not mandatory, these seven standard keys provide interoperability across security systems:

  • sub (Subject): The unique identifier of the user (e.g., UUID or user ID).
  • iss (Issuer): The authority that generated the token (e.g., https://auth.example.com).
  • aud (Audience): The recipient the token is intended for (e.g., https://api.example.com).
  • exp (Expiration Time): Unix timestamp marking when the token ceases to be valid.
  • nbf (Not Before): Timestamp identifying when the token becomes active.
  • iat (Issued At): Timestamp indicating when the token was created.
  • jti (JWT ID): A unique random identifier for the token, primarily used to prevent replay attacks.

B. Public and Private Claims

Custom claims that your specific application requires (such as role: "admin", tenant_id: "acme_corp", or plan: "pro").


[!CAUTION] A JWT is Signed, NOT Encrypted! Base64URL is merely an encoding format, not encryption. Anyone with access to the token string can decode the Payload in 2 milliseconds. Never store database passwords, API secrets, credit card numbers, or Social Security numbers inside a standard JWT payload.


3. The Signature: Preventing Tampering

The Signature is what makes a JWT trustworthy. Without the signature, any malicious user could edit their payload claim from "role": "user" to "role": "admin".

The signature is generated by taking the encoded Header, the encoded Payload, and combining them with a secret key through the algorithm declared in the header:

Signature = HMACSHA256(
  base64UrlEncode(Header) + "." + base64UrlEncode(Payload),
  secret_key
)

When the client sends the token back to the API server:

  1. The server extracts the Header and Payload.
  2. The server runs the exact same cryptographic function using its private server secret.
  3. If the resulting hash matches the token’s Signature, the server knows with 100% certainty that the data was not modified in transit. If an attacker changed even a single character in the payload, the hashes will not match, and the API responds with 401 Unauthorized.

Symmetric (HS256) vs. Asymmetric (RS256 / ES256) Signing

Feature Symmetric (HS256) Asymmetric (RS256 / ES256)
Key Architecture Single Shared Secret Key Public / Private Key Pair
Who Can Sign? Anyone who possesses the secret key Only the authorization server (holding Private Key)
Who Can Verify? Anyone who possesses the secret key Any service or microservice (holding Public Key)
Best Used For Monolithic backends, internal private APIs Microservices, OAuth2, Auth0, Supabase, Google Sign-In
Security Risk If a microservice leaks the secret, attackers can forge tokens Zero forgery risk; public keys can be distributed openly

In modern cloud environments, asymmetric signing (RS256/ES256) is the gold standard. A single Auth microservice signs tokens using a private RSA key, while dozens of downstream microservices verify incoming requests using the public certificate.

If you need to generate RSA or ECDSA key pairs for token signing, use our browser-based RSA & ECC Key Pair Generator.


The 4 Golden Rules of JWT Security

  1. Keep Access Token Lifespans Short: Set access token expiration (exp) to 10 to 15 minutes. Use long-lived Refresh Tokens stored securely in database tables to reissue short-lived access tokens. If an access token is intercepted, the attacker’s window of opportunity closes quickly.
  2. Never Store Sensitive Tokens in localStorage: JavaScript running in the browser can read localStorage. If your application suffers a Cross-Site Scripting (XSS) vulnerability, malicious third-party scripts can steal your user’s tokens. Store authentication tokens in HttpOnly; Secure; SameSite=Strict HTTP cookies, which browser JavaScript cannot access.
  3. Explicitly Whitelist Verification Algorithms: Early implementations suffered from the infamous "alg": "none" vulnerability, where attackers modified the header to "none", removed the signature, and bypassed verification. Modern JWT libraries prevent this by forcing developers to declare acceptable algorithms explicitly on the server (e.g., algorithms: ['RS256']).
  4. Use Strong Cryptographic Secrets: If using HS256, your shared secret must have at least 256 bits of entropy (32+ random characters). Weak secrets like "mysecretkey" can be cracked in seconds using offline dictionary attacks with hashcat. Generate high-entropy secrets using our Password & Secret Generator.

Frequently Asked Questions (FAQ)

What is the difference between a Session and a JWT?

Traditional sessions are stateful: the server creates a session ID, stores the session data in a central Redis or database table, and sets a cookie on the client. With every request, the server queries the database. A JWT is stateless: all user permissions reside inside the token itself, allowing backend APIs to scale horizontally without querying a shared session database.

How do you revoke or invalidate a JWT before it expires?

Because JWTs are stateless, you cannot “delete” a token from the client. To invalidate a token prematurely (e.g., upon password reset or account compromise), engineers use one of two methods:

  • Token Versioning: Storing a token_version: 2 integer in the user’s database record. When a user changes their password, increment the integer to 3. If a token presents version 2, reject it.
  • Revocation Blacklist: Storing revoked token IDs (jti) in a temporary high-speed Redis cache until their natural expiration timestamp elapses.

What is the difference between an ID Token and an Access Token?

  • ID Token: Intended for the client application. It contains user profile information (name, avatar, email) so the frontend UI can display user identity.
  • Access Token: Intended for the API resource server. It proves authorization to perform actions (read/write data) and should be validated on every API request.