Published on

JSON Web Tokens (JWT)

Authors
  • avatar
    Name
    Iraianbu A
    Twitter

Table of Contents

  1. Introduction
  2. Session tokens
  3. JWT vs Session tokens
  4. Structure
  5. How JWT Works
  6. JWT Authentication Flow
  7. Advantages
  8. Disadvantages
  9. Best Practices
  10. References

Introduction

JSON Web Tokens (JWT) is an open standard that specifies a compact and self-contained method for securely transmitting information between parties. JWTs are a type of token that can be utilized across multiple servers. They are akin to wristbands, allowing security personnel to easily identify individuals. JWTs are often used for API authentication, providing a single authorization that enables users to access the API multiple times.

  • Secure
  • Stateless
  • Compact
  • Flexible
JWT

Session tokens

Session tokens are encrypted strings used to identify a session between two parties. Consider a scenario where a user logs into a website and needs to be identified. The user is given a session token, which is stored in the server's memory. This token allows the server to identify the user and retrieve their data from the database. The session token is stored in the client's browser cookies.

JWT vs Session tokens

JWT and session tokens are both used to authenticate users, but they have some key differences.

Session tokensJWT
Looks up the session on every request to validate the userDecrypts the token and validates the signature on every request No DB Lookup
Authentication state (session) is stored on server sideStateless - No session stored in DB
Sessions are easy to invalidateSessions are hard to invalidate
Data is privateToken data can be decoded by anyone if they get access to the token
Vulnerable to CSRF attacksVulnerable to XSS attacks

Structure

A JWT is composed of three parts separated by dots:

Xxxxx.yyyy.zzz

  • Header (Algorithm and token type)
  • Payload (claims/data)
  • Signature (encoded header and payload)

These parts are encoded in a format called Base64, which turns data into a string that’s easy to send over the internet.

JWT

Source : https://stytch.com/blog/jwt-claims/

How JWT Works

  1. Header

It is the first part of the JWT. It contains the algorithm and token type.

  • Algorithm: The algorithm used to encode the token (e.g. HS256, RS256)
  • Token type: The type of token (e.g. JWT)
{
  "alg": "HS256",
  "typ": "JWT"
}
  1. Payload

It is the second part of the JWT. It contains the claims/data.

WARNING

Don't store sensitive data in the payload. The payload is not encrypted, but it is encoded (Base64).

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

Claims

Claims are statements about an entity (e.g., user) and additional metadata. There are three types of claims:

  1. Registered claims

Registered claims are predefined claims that are not mandatory but recommended.

  • iss (issuer) : The issuer of the JWT
  • sub (subject) : The subject of the JWT (e.g., user ID)
  • aud (audience) : Recipient for which the JWT is intended
  • exp (expiration time) : Time after which the JWT expires
  • nbf (not before time) : Time before which the JWT must not be accepted
  • iat (issued at time) : Time at which the JWT was issued
  • jti (JWT ID) : Unique identifier for the JWT
  1. Public claims

These are custom claims that anyone can see, like a person's name or email. If you make public claims, you should register them or use unique names to avoid conflicts and ensure you control the naming.

  1. Private claims

These are custom claims meant for your application only. They include specific details like an employee's ID or department, unlike public claims which are more general.

  1. Signature

It is the third part of the JWT. It contains the encoded header and payload. The server uses the same algorithm specified in the header to create the signature.

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

JWT Authentication Flow

  1. A user provides their credentials (e.g., username and password) and sends them to the server.
  2. The server validates the credentials. If they are correct, the server generates a JWT containing the user's information (in a claim) and signs it with a secret key.
  3. The server sends the JWT back to the user.
  4. The user stores the JWT (usually in the browser's local storage or as a cookie) and includes it in the Authorization header in subsequent requests to the server.
  5. When the user sends a new request with the JWT, the server decodes the JWT, and verifies its signature. If the token is valid, the server processes the request and returns the appropriate response.

Advantages

  • Cross-domain support
  • Self-contained and extensible
  • Stateless

Disadvantages

  • Token size
  • No Token Invalidation
  • Security risks
  • Limited Token Updates

Best Practices

  • Keep tokens small
  • Don't store sensitive data in the payload
  • Have short expiration times
  • Implement refresh tokens
  • Set the issuer , audience properties in the payload
  • Use asymmetric encryption for signing tokens

References

  1. JWT
  2. JWT Claims
  3. Descope
  4. Auth0