What is JWT

JWT (JSON Web Token) is an open standard (RFC 7519) that defines a compact and self-contained way to securely transmit information between parties as a JSON object. This information can be verified and trusted because it's digitally signed.

Structure of a JWT

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

text
xxxxx.yyyyy.zzzzz

1. Header

Contains metadata about the token:

  • Type of token (typically "JWT")

  • Signing algorithm used (e.g., HMAC SHA256, RSA)

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

2. Payload

Contains the claims (statements about an entity and additional data):

  • Registered claims: Predefined claims like iss (issuer), exp (expiration time), sub (subject)

  • Public claims: Custom claims defined by users

  • Private claims: Custom claims shared between parties

json
{
  "sub": "1234567890",
  "name": "John Doe",
  "admin": true,
  "iat": 1516239022
}

3. Signature

Created by encoding the header and payload, then signing them with a secret key:

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

How JWT Works

Authentication Flow

  1. User logs in with credentials

  2. Server validates credentials and generates a JWT

  3. Server returns the JWT to the client

  4. Client stores the JWT (usually in localStorage or cookies)

  5. Client includes JWT in subsequent requests (typically in Authorization header)

  6. Server verifies the JWT signature and grants access

Example Request

text
GET /api/protected
Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c

Key Characteristics

✅ Advantages

  • Stateless: Server doesn't need to store session information

  • Compact: Can be sent via URL, POST parameter, or HTTP header

  • Self-contained: Contains all necessary user information

  • Secure: Can be signed and optionally encrypted

  • Cross-domain: Works well with CORS and multiple domains

❌ Limitations

  • Cannot revoke: Once issued, tokens remain valid until expiration

  • Size: Can become large with many claims

  • Storage: Must be stored securely on client side

Common Use Cases

  1. Authentication: Single sign-on (SSO), stateless sessions

  2. Authorization: Access control for APIs and resources

  3. Information Exchange: Securely transmitting data between parties

Security Best Practices

  1. Use HTTPS always

  2. Set short expiration times (e.g., 15 minutes)

  3. Store securely (HttpOnly cookies for web apps)

  4. Validate signature on every request

  5. Use strong secrets for signing

  6. Include minimal data in payload (avoid sensitive info)

To Top