multitools.ovh

JWT Encoder & Decoder

Encode and decode JSON Web Tokens (JWT) with header, payload, and signature visualization

Header
Payload
Signature
Abstract: JSON Web Tokens (JWT) represent a compact, URL-safe means of representing claims to be transferred between two parties. This comprehensive analysis explores the technical architecture, implementation methodologies, security considerations, and practical applications of JWT in modern web development and distributed systems.

1. Introduction and Definition

JSON Web Token (JWT) is an open standard (RFC 7519) that defines a compact and self-contained way for securely transmitting information between parties as a JSON object. This information can be verified and trusted because it is digitally signed. JWTs can be signed using a secret (with the HMAC algorithm) or a public/private key pair using RSA or ECDSA.

The primary purpose of JWT is to provide a stateless authentication mechanism that enables secure information exchange in distributed systems, particularly in microservices architectures and single-page applications (SPAs).

2. JWT Structure and Architecture

2.1 Three-Part Structure

A JWT consists of three parts separated by dots (.), which are:

  • Header - Contains metadata about the token
  • Payload - Contains the claims (user data)
  • Signature - Ensures token integrity
header.payload.signature Example: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c

2.2 Header Component

The header typically consists of two parts: the type of the token (JWT) and the signing algorithm being used, such as HMAC SHA256 or RSA.

{ "alg": "HS256", "typ": "JWT", "kid": "key-id-123" }

Common header parameters include:

Parameter Description Example
alg Algorithm used for signing HS256, RS256, ES256
typ Token type JWT
kid Key ID for key rotation key-2023-01
cty Content type JWT (for nested JWTs)

2.3 Payload Component

The payload contains the claims, which are statements about an entity (typically, the user) and additional data. There are three types of claims:

2.3.1 Registered Claims

These are predefined claims that provide a set of useful, interoperable claims:

{ "iss": "https://auth.multitools.ovh", // Issuer "sub": "user123", // Subject "aud": "https://api.multitools.ovh", // Audience "exp": 1516239022, // Expiration Time "nbf": 1516239022, // Not Before "iat": 1516239022, // Issued At "jti": "unique-token-id-123" // JWT ID }

2.3.2 Public Claims

These can be defined at will by those using JWTs. To avoid collisions, they should be defined in the IANA JSON Web Token Registry or be defined as a URI that contains a collision-resistant namespace.

2.3.3 Private Claims

These are custom claims created to share information between parties that agree on using them:

{ "user_id": 12345, "username": "john.doe", "roles": ["user", "admin"], "permissions": ["read", "write", "delete"], "tenant_id": "company-abc", "session_id": "sess-789" }

2.4 Signature Component

The signature is used to verify that the sender of the JWT is who it says it is and to ensure that the message wasn't changed along the way. The signature is created by combining the encoded header, encoded payload, a secret, and the algorithm specified in the header.

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

3. How JWT Works: Complete Flow Analysis

Authentication Flow

1. User Login
2. Server Validates
3. JWT Generated
4. Token Returned


5. Client Stores JWT
6. Include in Requests
7. Server Validates
8. Access Granted

3.1 Token Generation Process

When a user successfully authenticates, the server generates a JWT through the following process:

// Step 1: Create Header const header = { "alg": "HS256", "typ": "JWT" }; // Step 2: Create Payload const payload = { "sub": "user123", "name": "John Doe", "iat": Math.floor(Date.now() / 1000), "exp": Math.floor(Date.now() / 1000) + (60 * 60), // 1 hour "roles": ["user"] }; // Step 3: Encode Header and Payload const encodedHeader = base64UrlEncode(JSON.stringify(header)); const encodedPayload = base64UrlEncode(JSON.stringify(payload)); // Step 4: Create Signature const signature = HMACSHA256( encodedHeader + "." + encodedPayload, secretKey ); // Step 5: Combine to form JWT const jwt = encodedHeader + "." + encodedPayload + "." + signature;

3.2 Token Validation Process

When the server receives a JWT, it validates the token through these steps:

// Step 1: Split the token const [headerB64, payloadB64, signatureB64] = jwt.split('.'); // Step 2: Decode header and payload const header = JSON.parse(base64UrlDecode(headerB64)); const payload = JSON.parse(base64UrlDecode(payloadB64)); // Step 3: Verify signature const expectedSignature = HMACSHA256( headerB64 + "." + payloadB64, secretKey ); if (expectedSignature !== signatureB64) { throw new Error('Invalid signature'); } // Step 4: Check expiration if (payload.exp < Math.floor(Date.now() / 1000)) { throw new Error('Token expired'); } // Step 5: Validate other claims if (payload.iss !== expectedIssuer) { throw new Error('Invalid issuer'); }

4. Cryptographic Algorithms and Security

4.1 Supported Algorithms

Algorithm Type Key Requirement Security Level Performance
HS256 HMAC with SHA-256 Shared Secret High Fast
HS384 HMAC with SHA-384 Shared Secret Very High Fast
HS512 HMAC with SHA-512 Shared Secret Very High Fast
RS256 RSA with SHA-256 Public/Private Key Pair Very High Moderate
RS384 RSA with SHA-384 Public/Private Key Pair Extremely High Moderate
RS512 RSA with SHA-512 Public/Private Key Pair Extremely High Moderate
ES256 ECDSA with SHA-256 Elliptic Curve Key Pair Very High Good
ES384 ECDSA with SHA-384 Elliptic Curve Key Pair Extremely High Good
ES512 ECDSA with SHA-512 Elliptic Curve Key Pair Extremely High Good

4.2 Security Considerations

Critical Security Guidelines

Never use the "none" algorithm in production! This algorithm provides no security and should only be used for testing purposes.

4.2.1 Key Management

Proper key management is crucial for JWT security:

// Good: Strong secret generation const crypto = require('crypto'); const secret = crypto.randomBytes(64).toString('hex'); // Bad: Weak or predictable secret const weakSecret = "mypassword123"; // Never do this! // Good: Key rotation strategy const keyRotation = { currentKey: "key-2023-12", previousKey: "key-2023-11", rotationInterval: 30 * 24 * 60 * 60 * 1000 // 30 days };

4.2.2 Token Storage Security

Different storage methods have different security implications:

Storage Method XSS Vulnerability CSRF Vulnerability Recommendation
localStorage High Low Avoid for sensitive apps
sessionStorage High Low Better than localStorage
HttpOnly Cookie Low High Use with CSRF protection
Secure + HttpOnly Cookie Low Moderate Recommended approach
Memory (JavaScript variable) Moderate Low Good for short sessions

5. Why Use JWT: Advantages and Use Cases

Advantages

  • Stateless Authentication: No need to store session information on the server
  • Scalability: Perfect for distributed systems and microservices
  • Cross-Domain Support: Works across different domains and services
  • Self-Contained: All necessary information is included in the token
  • JSON Format: Easy to parse and work with in any programming language
  • Compact Size: Smaller than SAML tokens, efficient for HTTP headers
  • Mobile Friendly: Ideal for mobile applications and APIs
  • Flexible Claims: Can include custom user information and permissions

Disadvantages

  • Token Size: Can become large with many claims
  • Security Concerns: Vulnerable if not implemented correctly
  • Token Revocation: Difficult to revoke tokens before expiration
  • Secret Management: Requires careful handling of signing keys
  • Debugging Complexity: Can be harder to debug than traditional sessions
  • Storage Vulnerabilities: Client-side storage has security implications
  • Clock Synchronization: Requires synchronized clocks for exp/iat claims

5.1 Primary Use Cases

Single Sign-On (SSO)

JWT enables seamless authentication across multiple applications and services within an organization's ecosystem.

API Authentication

Stateless authentication for RESTful APIs, eliminating the need for server-side session storage.

Microservices Architecture

Enables secure service-to-service communication without centralized session management.

Mobile Applications

Lightweight authentication mechanism suitable for mobile apps with intermittent connectivity.

Information Exchange

Secure transmission of information between parties with signature verification capabilities.

Copied to clipboard!