Home/Blog/Cybersecurity/JSON Web Tokens Explained: How JWTs Work for Authentication
Cybersecurity

JSON Web Tokens Explained: How JWTs Work for Authentication

Understand how JSON Web Tokens (JWTs) work for authentication and authorization. Learn about JWT structure, claims, signing algorithms, and security best practices.

By Inventive HQ Team
JSON Web Tokens Explained: How JWTs Work for Authentication

JSON Web Tokens (JWTs) have become the standard for authentication in modern web applications and APIs. Understanding how they work is essential for developers building secure applications and security professionals analyzing authentication systems.

What Is a JWT?

A JWT is a compact, URL-safe token format that securely transmits information between parties as a JSON object. The information can be verified and trusted because it's digitally signed.

JWTs are commonly used for:

  • Authentication: After login, each subsequent request includes the JWT, allowing access to routes, services, and resources
  • Information exchange: JWTs can securely transmit information between parties because they're signed

JWT Structure

A JWT consists of three parts separated by dots: header.payload.signature

eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.
eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.
SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c

The header typically contains the token type (JWT) and the signing algorithm:

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

Payload

The payload contains claims---statements about the user and additional metadata:

{
  "sub": "1234567890",
  "name": "John Doe",
  "email": "[email protected]",
  "role": "admin",
  "iat": 1516239022,
  "exp": 1516242622
}

Registered claims are predefined:

  • iss (issuer): Who issued the token
  • sub (subject): Who the token is about (usually user ID)
  • aud (audience): Who the token is intended for
  • exp (expiration): When the token expires
  • iat (issued at): When the token was created
  • nbf (not before): Token not valid before this time

Custom claims can include any data you need, like user roles or permissions.

Signature

The signature verifies the token wasn't tampered with:

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

How JWT Authentication Works

  1. User logs in with credentials
  2. Server validates credentials and generates a JWT
  3. JWT is returned to the client (stored in localStorage, sessionStorage, or cookie)
  4. Client includes JWT in the Authorization header for subsequent requests
  5. Server validates JWT signature and grants access
Authorization: Bearer eyJhbGciOiJIUzI1NiIs...

Signing Algorithms

Symmetric algorithms (HS256, HS384, HS512) use the same secret key to sign and verify. Simple but requires secure key distribution.

Asymmetric algorithms (RS256, RS384, RS512, ES256) use a private key to sign and a public key to verify. Better for distributed systems where multiple services need to verify tokens.

JWT Security Best Practices

Set Short Expiration Times

JWTs can't be revoked once issued. Short expiration times (15 minutes to 1 hour) limit the window of vulnerability if a token is compromised.

Use HTTPS Only

JWTs are credentials. Always transmit them over HTTPS and set the Secure cookie flag if storing in cookies.

Don't Store Sensitive Data in Payload

The payload is only base64-encoded, not encrypted. Anyone can decode and read it. Never include passwords, API keys, or sensitive personal data.

Validate Everything

Always verify:

  • The signature is valid
  • The token hasn't expired (exp)
  • The issuer is correct (iss)
  • The audience is correct (aud)

Use Strong Secrets

For HMAC algorithms, use secrets at least 256 bits long. Generate them securely---never use simple phrases.

Common JWT Vulnerabilities

Algorithm confusion: Attackers change alg to none or switch from RS256 to HS256 using the public key as the secret. Always explicitly specify allowed algorithms when verifying.

Missing signature validation: Never skip signature verification. A token without validation is just a base64 string anyone can create.

Token sidejacking: If tokens are stored insecurely (accessible via XSS), attackers can steal them. Use HttpOnly cookies or secure storage.

Long expiration times: Tokens valid for days or weeks give attackers a large window to use stolen tokens.

When to Use JWTs

Good use cases:

  • Stateless authentication across multiple services
  • Single sign-on (SSO)
  • Short-lived access tokens
  • Mobile app authentication

Consider alternatives when:

  • You need to revoke tokens immediately
  • Sessions are long-lived
  • You're only authenticating with one server

Decode and Inspect JWTs

Use our JWT Decoder to:

  • Decode any JWT without the secret
  • View header and payload claims
  • Check expiration status
  • Identify the signing algorithm

The decoder runs entirely in your browser---your tokens are never sent to any server.

Key Takeaways

  1. JWTs have three parts: header, payload, and signature
  2. The payload is encoded, not encrypted---don't store secrets
  3. Always validate signatures and expiration
  4. Use short expiration times since JWTs can't be revoked
  5. Choose the right signing algorithm for your architecture

JWTs provide a powerful, flexible authentication mechanism when implemented correctly. Understanding their structure and security implications is essential for building secure applications.

Don't wait for a breach to act

Get a free security assessment. Our experts will identify your vulnerabilities and create a protection plan tailored to your business.

What is a JWT (JSON Web Token)? A Complete Guide

What is a JWT (JSON Web Token)? A Complete Guide

Learn what JSON Web Tokens are, how they work, and why they

Is JWT decoding safe?

Is JWT decoding safe?

Explore the security implications of JWT decoding, common vulnerabilities, and best practices to safely handle JWTs in your applications.

JWT Security Best Practices: Token Signing, Validation, and Common Vulnerabilities

JWT Security Best Practices: Token Signing, Validation, and Common Vulnerabilities

Master JWT security with this comprehensive guide covering token structure, signing algorithms, validation best practices, secure storage, and common vulnerabilities like algorithm confusion and token leakage.

Formal Security Models Explained: Bell-LaPadula, Biba, Clark-Wilson, and Beyond

Formal Security Models Explained: Bell-LaPadula, Biba, Clark-Wilson, and Beyond

Master the formal security models that underpin all access control systems. This comprehensive guide covers Bell-LaPadula, Biba, Clark-Wilson, Brewer-Nash, lattice-based access control, and how to choose the right model for your organization.

Biometric Authentication: Understanding FAR, FRR, and CER for Security Professionals

Biometric Authentication: Understanding FAR, FRR, and CER for Security Professionals

Master the critical metrics behind biometric authentication systems including False Acceptance Rate (FAR), False Rejection Rate (FRR), and Crossover Error Rate (CER). Learn how to evaluate, tune, and deploy biometric systems across enterprise, consumer, and high-security environments.

Database Inference & Aggregation Attacks: The Complete Defense Guide

Database Inference & Aggregation Attacks: The Complete Defense Guide

Learn how inference and aggregation attacks exploit aggregate queries and combined data to reveal protected information, and discover proven countermeasures including differential privacy, polyinstantiation, and query restriction controls.