What is JWT (JSON Web Token)?

Learn what JWT (JSON Web Token) is, how it works, and why it is used for stateless authentication and authorization in APIs, microservices, mobile apps, and SSO. Understand JWT structure, claims, signatures, security best practices, and edge validation with Azion.

While an API Gateway focuses on orchestration, routing, and operational traffic governance, API Security (WAAP) focuses on protecting application logic. The Gateway ensures the request reaches its destination; security ensures the request isn’t malicious (by inspecting payloads and mitigating OWASP API Top 10). In modern architectures, unifying these functions on the Global computing platform is the standard to align protection and performance.


JWT (JSON Web Token) is an open standard (RFC 7519) for securely transmitting information between parties as a compact, URL-safe JSON object. JWTs encode claims (assertions about an entity) that are digitally signed using cryptographic algorithms, enabling stateless authentication and authorization in web applications and APIs.

Last updated: 2026-04-01

How JWT Works

JWTs consist of three Base64URL-encoded parts separated by dots: header, payload, and signature. The header identifies the token type and signing algorithm. The payload contains claims (user ID, roles, expiration time). The signature ensures token integrity by combining encoded header, encoded payload, and a secret key using the specified algorithm.

When a user authenticates, the server generates a JWT containing identity claims and signs it with a secret key. The client stores the JWT (typically in localStorage or cookies) and includes it in subsequent requests via the Authorization header. Servers verify the signature and extract claims without storing session state—enabling stateless authentication.

JWTs support two types of security: signed tokens (JWS) verify integrity and authenticity using HMAC, RSA, or ECDSA algorithms. Encrypted tokens (JWE) provide confidentiality by encrypting payload content. Most implementations use signed tokens for authentication, relying on TLS for transport security.

When to Use JWT

Use JWT when you need:

  • Stateless authentication for APIs and microservices
  • Single sign-on (SSO) across multiple applications
  • Authorization claims embedded in token (roles, permissions)
  • Mobile and SPA applications requiring token-based auth
  • Federated identity systems passing identity between services
  • Short-lived access tokens with optional refresh tokens

Do not use JWT when you need:

  • Server-side session management with immediate revocation
  • Highly sensitive data requiring encryption at rest
  • Large claims exceeding token size recommendations (>8KB)
  • Frequent claim updates requiring immediate propagation
  • Compliance requirements for server-logged session activity

Signals You Need JWT

  • Stateless API architecture scaling horizontally across servers
  • Microservices requiring identity propagation without central session store
  • Mobile applications unable to use server-side sessions efficiently
  • Single sign-on across multiple domains or applications
  • Third-party applications accessing your APIs on behalf of users
  • Need to embed authorization decisions directly in tokens

Metrics and Measurement

Security Metrics:

  • Token validation success rate: Percentage of tokens validating successfully (target: >99%)
  • Invalid token attempts: Failed validations due to expiration, bad signature, or malformed tokens
  • Token replay prevention: Zero successful replay attacks (implement nonces or short expiration)
  • Algorithm confusion attacks: Zero instances (prevent by validating algorithm explicitly)

Performance Metrics:

  • Token generation time: Time to create and sign JWT (typically under 5ms)
  • Token validation time: Time to verify signature and extract claims (typically under 2ms)
  • Token size: Header + payload + signature bytes (target: under 4KB for most use cases)
  • Bandwidth overhead: Token transmitted with every authenticated request

Operational Metrics:

  • Token expiration rate: Percentage of requests failing due to expired tokens
  • Refresh token usage: Frequency of token refresh operations
  • Claim size distribution: Average and maximum payload size across tokens

According to OAuth 2.0 best practices (RFC 8725), JWT access tokens should have short lifetimes (5-60 minutes) to limit exposure from token theft. Refresh tokens enable longer sessions without compromising access token security.

JWT Structure

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

Identifies token type and signing algorithm (HMAC, RSA, ECDSA). Base64URL encoded.

Payload

{
"sub": "user123",
"name": "John Doe",
"role": "admin",
"iat": 1712345678,
"exp": 1712349278
}

Contains claims: registered claims (iss, sub, aud, exp, iat, nbf), public claims, and private claims. Base64URL encoded.

Signature

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

Ensures token integrity. Verification confirms token not tampered. Algorithm must match header.

Real-World Use Cases

API Authentication:

  • Stateless authentication for REST and GraphQL APIs
  • Microservices authentication without central session store
  • Bearer token authentication in Authorization header
  • Claims-based authorization (roles, permissions, scopes)

Single Sign-On (SSO):

  • Identity propagation across multiple applications
  • Federated authentication between organizations
  • OIDC (OpenID Connect) ID tokens for user identity
  • Session management across domains

Mobile Applications:

  • Token-based auth for iOS, Android, React Native
  • Persistent authentication without server sessions
  • Secure credential storage with refresh tokens
  • Offline capability with cached tokens

Third-Party Authorization:

  • OAuth 2.0 access tokens for API access delegation
  • Service-to-service authentication
  • Machine-to-machine (M2M) communication
  • API gateway authentication

Stateless Workflows:

  • Password reset tokens with expiration
  • Email verification tokens
  • One-time action tokens (invitation links, magic links)
  • Time-limited access grants

Common Mistakes and Fixes

Mistake: Storing sensitive data in JWT payload without encryption Fix: JWT payloads are Base64 encoded, not encrypted. Anyone can decode. Store only non-sensitive claims (user ID, roles). Never store passwords, credit cards, or PII. Use JWE for encrypted payloads if needed.

Mistake: Using long-lived access tokens Fix: Access tokens should expire in 5-60 minutes. Use refresh tokens for long sessions. Implement token rotation for refresh tokens. Long-lived access tokens increase exposure window from token theft.

Mistake: Not validating token algorithm Fix: Validate algorithm matches expected value (HS256, RS256). Reject tokens with “none” algorithm. Algorithm confusion attacks exploit algorithm mismatch between header and verification logic.

Mistake: Storing JWT in localStorage vulnerable to XSS Fix: Store JWT in HttpOnly, Secure, SameSite cookies. This prevents JavaScript access (XSS protection). CSRF protection required for cookies. Evaluate trade-offs: localStorage (XSS risk) vs cookies (CSRF risk).

Mistake: Not implementing token revocation Fix: JWTs cannot be revoked before expiration without additional infrastructure. Implement token blacklist, short expiration times, or version-based invalidation. Balance security with stateless benefits.

Mistake: Using JWT for server-side sessions Fix: JWTs enable stateless auth. If you need immediate revocation, server-side logging, or large session data, use traditional server-side sessions. Don’t force JWT when sessions are more appropriate.

Frequently Asked Questions

What is the difference between JWT and session tokens? Session tokens reference server-side session data. Servers must look up session state. JWTs embed claims directly in token, enabling stateless authentication without server-side storage. Sessions enable immediate revocation; JWTs provide stateless scalability.

How do I invalidate JWT before expiration? JWTs cannot be invalidated without additional infrastructure. Options: implement token blacklist (requires state), use short expiration times, include version claim invalidated on password change, use refresh tokens with immediate revocation capability.

Should I use HMAC or RSA signatures? HMAC (HS256) uses shared secret—simple, fast, but both parties share secret. RSA (RS256) uses public/private key pair—issuer signs with private key, verifiers use public key. Use HMAC for single-service deployments. Use RSA for multi-service architectures where services verify without signing ability.

What claims should I include in JWT? Include minimum necessary claims: subject (user ID), issuer, audience, expiration (exp), issued-at (iat). Add authorization claims: roles, permissions, scopes. Avoid sensitive data (PII, passwords). Keep payload small (under 4KB) to minimize bandwidth overhead.

Can JWT payload be encrypted? Yes, JWT supports encryption through JSON Web Encryption (JWE). JWE encrypts payload content for confidentiality. Most implementations use signed JWTs (JWS) relying on TLS for transport security. Use JWE when payload contains sensitive data or token may be logged.

How do I handle JWT in microservices? API gateway validates JWT and propagates user identity to services. Services verify signature using shared secret (HMAC) or public key (RSA). Services extract claims for authorization decisions. Refresh token handling centralized at auth service.

What is the difference between access token and refresh token? Access tokens authorize API access and have short lifetimes (minutes). Refresh tokens obtain new access tokens and have long lifetimes (days, weeks). Access tokens sent with every request; refresh tokens used only for token refresh. Refresh tokens require secure storage.

How This Applies in Practice

JWT enables stateless authentication critical for modern API architectures. Microservices verify tokens independently without central session store. Mobile and SPA applications use token-based auth for seamless user experience.

Implementation Strategy:

  • Choose signing algorithm (HMAC for simplicity, RSA for multi-service)
  • Define claim structure: subject, issuer, audience, expiration, authorization claims
  • Implement token generation with secure secret key management
  • Deploy token validation middleware in API gateways and services
  • Handle token expiration with refresh tokens
  • Implement secure token storage (HttpOnly cookies for web, secure storage for mobile)

Security Best Practices:

  • Use short-lived access tokens (5-60 minutes)
  • Validate algorithm, expiration, issuer, audience
  • Store secrets securely (environment variables, secret management)
  • Implement token refresh with refresh token rotation
  • Use HTTPS for all token transmission
  • Implement rate limiting on token validation endpoints

Architecture Decisions:

  • Use JWT for stateless APIs and microservices
  • Consider server-side sessions for applications requiring immediate revocation
  • Implement API gateway pattern for centralized token validation
  • Use asymmetric keys (RSA, ECDSA) for multi-team verification
  • Plan for token refresh and session management

JWT on Azion

Azion Functions validate JWT at the edge:

  1. JWT validation in Functions before forwarding requests to origin
  2. Firewall rules enforce authentication requirements
  3. Extract claims for authorization decisions at the edge
  4. Rate limiting prevents token validation abuse
  5. Real-Time Metrics monitor authentication events
  6. Caching for public keys (RS256) or JWKS endpoints

Azion’s distributed network authenticates requests globally, reducing latency for token validation and protecting origin infrastructure.

Learn more about Functions, API Security, and Firewall.


Sources:

stay up to date

Subscribe to our Newsletter

Get the latest product updates, event highlights, and tech industry insights delivered to your inbox.