Description

A JSON Web Token (JWT) is a compact, URL-safe means of representing claims securely between two parties. It’s a widely adopted token format used in modern web authentication and authorization protocols — particularly in OAuth 2.0, OpenID Connect, and API security systems.

JWTs are self-contained tokens that encode claims (such as user ID, roles, and permissions) and can be verified using a digital signature. This allows for stateless authentication, where the server does not need to store session data — all necessary information is embedded directly in the token.

JWT Structure

A JWT consists of three Base64-URL encoded parts, separated by dots (.):

..

1. Header

Specifies the token type and algorithm used for signing.

{
  "alg": "HS256",
  "typ": "JWT"
}

2. Payload

Contains the claims, or statements about the user or subject.

{
  "sub": "1234567890",
  "name": "John Doe",
  "admin": true,
  "exp": 1724500000
}

3. Signature

Used to verify the token’s integrity. Created by encoding the header and payload, then signing with a secret key or private key:

HMACSHA256(
  base64UrlEncode(header) + "." + base64UrlEncode(payload),
  secret
)

Token Example

Encoded JWT:

eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9
.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiYWRtaW4iOnRydWV9
.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c

You can decode this using tools like jwt.io to view the payload.

Standard JWT Claims

ClaimDescription
issIssuer (who created the token)
subSubject (user ID)
audAudience (intended recipient)
expExpiration time (UNIX timestamp)
nbfNot before (when token becomes valid)
iatIssued at (when token was created)
jtiJWT ID (unique identifier)

You can also include custom claims, such as role, department, tenant_id.

Use Cases

1. User Authentication (Stateless Login)

After login, the server issues a JWT. The client stores it (e.g., in memory or localStorage) and sends it in every subsequent request.

2. API Authorization

APIs validate JWTs before allowing access. The token includes scopes or roles to determine what the user can do.

3. Single Sign-On (SSO)

JWTs are used by identity providers to pass user info to client applications securely.

4. Mobile App Authentication

JWTs are ideal for mobile or SPA (single-page application) architectures due to their compact, portable format.

Advantages of JWT

Stateless Authentication
No server-side session needed; reduces server load.

Compact and URL-Safe
Can be passed via headers, query strings, or cookies.

Self-Contained
All user info and metadata are stored within the token.

Cryptographically Secure
Tampering with a token invalidates the signature.

Widely Supported
Libraries exist for every major language and framework.

JWT vs Session

FeatureJWTTraditional Session
StorageClient-sideServer-side
ScalabilityHighly scalableHarder to scale across servers
RevocationHarder (requires blacklist)Easy (destroy session on server)
StatelessYesNo
SecurityRequires careful token handlingSession ID protected by cookie

Security Considerations

❗ JWTs are powerful, but can introduce risks if misused:

  • Always sign JWTs using strong algorithms (e.g., RS256 or HS256).
  • Validate expiration (exp) claim strictly.
  • Do not store sensitive data like passwords or credit cards inside JWTs.
  • Use short token lifespans and refresh tokens for long sessions.
  • Use HTTPS to avoid token leakage in transit.
  • Consider token revocation mechanisms (e.g., blocklists or token IDs).

Token Expiration and Refresh

JWTs typically have a short access token lifespan (e.g., 5–15 minutes), after which the client uses a refresh token to request a new JWT.

Example Payload with Expiration

{
  "sub": "user123",
  "iat": 1723000000,
  "exp": 1723003600
}

If the exp claim is in the past, the token is expired and must be refreshed or rejected.

Signed vs Encrypted JWTs

  • Signed JWT (JWS)
    Verifies integrity; readable by the recipient. Most common.
  • Encrypted JWT (JWE)
    Used when token confidentiality is required (rare). Uses alg + enc headers.

Popular JWT Libraries

LanguageLibrary
JavaScriptjsonwebtoken, auth0/jwt-decode
PythonPyJWT, Authlib
JavaNimbus JOSE+JWT, jjwt
.NETSystem.IdentityModel.Tokens.Jwt
Gogolang-jwt/jwt
PHPfirebase/php-jwt

Examples

Create a JWT (Node.js + jsonwebtoken)

const jwt = require("jsonwebtoken");

const payload = {
  sub: "user123",
  role: "admin",
  exp: Math.floor(Date.now() / 1000) + (60 * 15) // 15 minutes
};

const token = jwt.sign(payload, "mySecretKey");

Decode a JWT (Python + PyJWT)

import jwt

decoded = jwt.decode(token, "mySecretKey", algorithms=["HS256"])
print(decoded["sub"])

Send JWT in HTTP Request

GET /dashboard HTTP/1.1
Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...

Related Keywords

Access Token
API Security
Authentication
Authorization
Bearer Token
Claims
Digital Signature
Encrypted Token
Header Payload Signature
ID Token
JWT Claims
JWT Signature
OAuth2
OpenID Connect
Refresh Token
Session Token
Single Sign On
Stateless Authentication
Token Expiration
Token Revocation