Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

JWT based authentication

JWT (JSON Web Token) 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. Its characteristics are:

  • Compact: JWTs are small in size, making them easy to send through URLs, POST parameters, or HTTP headers
  • Self-contained: The payload contains all the required information about the user, avoiding querying the database multiple times
  • Stateless: No server-side session storage is required
  • Digitally Signed: Ensures the token hasn’t been tampered with

Structure

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

eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiYWRtaW4iOnRydWUsImlhdCI6MTUxNjIzOTAyMiwiZXhwIjoxNTE2MjQyNjIyfQ.4Adcj0vTzBLb_k4vBz4KgvwjuU34w_R11K7g4qHQ3Qg

The header typically consists of two parts:

  • Type: JWT
  • Signing Algorithm: HMAC SHA256, RSA, etc This JSON is then Base64Url encoded to form the first part of the JWT.
{
  "alg": "HS256",
  "typ": "JWT"
}

Payload

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

Registered Claims

Predefined claims that are recommended but not mandatory:

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

Public Claims

Custom claims that can be defined by those using JWTs. Should be defined in the IANA JSON Web Token Registry or use collision-resistant names.

Private Claims

Custom claims agreed upon between parties.

This JSON is then Base64Url encoded to form the second part of the JWT.

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

Signature

The signature is used to verify that the sender of the JWT is who it says it is and the message wasn’t changed along the way. The signature is created by taking:

  • The encoded header
  • The encoded payload
  • A secret key
  • The algorithm specified in the header
HMACSHA256(
  base64UrlEncode(header) + "." + base64UrlEncode(payload),
  secret
)

Authentication Flow

Basic JWT Flow

  • User Login: User sends credentials (username/password) to the server
  • Server Verification: Server verifies credentials against the database
  • Token Generation: If valid, server creates a JWT with user information and signs it
  • Token Delivery: Server sends JWT back to the client
  • Token Storage: Client stores the JWT in cookies or keystore (if on Android or desktop)
  • Subsequent Requests: Client includes JWT in the Authorization header for protected routes
  • Token Verification: Server verifies the signature and extracts user information
  • Access Grant/Deny: Server grants or denies access based on token validity

Refresh Token Pattern

For modern authentication in applications, we generate two tokens: an access token (a JWT token) and a refresh token (an opaque token).

Token Creation Flow

  • User Login: User sends credentials (username/password) to the server
  • Server Verification: Server verifies credentials against the database
  • Token Generation: If valid, server creates two tokens:
    • Access token with user information (JWT, short-lived - 1d)
    • Opaque refresh token (stored in database, longer-lived - 30d)
  • Token Delivery: Server sends both tokens back to the client
  • Token Storage: Client stores the tokens in cookies or device storage
  • Subsequent Requests: Client includes JWT in the Authorization header for protected routes
  • Token Verification: Server verifies the signature and extracts user information
  • Access Grant/Deny: Server grants or denies access based on token validity

Token Refresh Flow

  • Access Denied: Server denies access due to token expiry, returns 401 Unauthorized to client
  • Refresh Request: Client sends the refresh token to the server
  • Server Verification: Server verifies if the refresh token is valid and not expired
  • Token Generation: New token pair is generated
  • Token Rotation: Old refresh token is invalidated (optional but recommended)
  • Token Delivery: Server sends new tokens back to the client
  • Token Storage: Client updates stored tokens

Recommendation

  • Implement Family ID to track refresh token theft.
  • Store tokens in HTTP only cookies