backend / rest apis / 02_jwt_auth.md

JWT Authentication: What, When, and How

3 interview angles 3 min read source

JWT Authentication: What, When, and How

What is JWT Authentication?

JWT (JSON Web Token) is a compact, URL-safe token format used for securely transmitting information between parties. It is commonly used for authentication and authorization in web applications.

A JWT token consists of three parts:

  1. Header: Information about how the token is encoded and the signing algorithm used (e.g., HS256).
  2. Payload: Contains the claims (user data, expiration time, permissions).
  3. Signature: A cryptographic signature to verify that the token hasn’t been tampered with.

A full JWT looks like:

<base64-encoded-header>.<base64-encoded-payload>.<signature>

When to Use JWT

Use JWT Authentication when:

  • Building stateless APIs (e.g., RESTful APIs).
  • You want scalable authentication without server-side session storage.
  • Your services need to be decentralized (microservices communicating across systems).
  • You require token-based SSO (Single Sign-On).
  • You want a client to authenticate once and then use a token for multiple requests without logging in again.

When NOT to Use JWT

Avoid using JWT if:

  • You need to easily revoke tokens (hard with JWT without additional tracking like blacklists).
  • You have short-lived sessions (e.g., admin panels) where sessions should be easily invalidated.
  • Token size matters (JWTs can be large compared to simple session IDs).
  • Your security requirements demand absolute control over session state (session-based auth is more flexible).

In some cases, traditional session cookies or OAuth2 with opaque tokens are better choices.


JWT Token Structure Breakdown

Part Purpose
Header Algorithm and token type
Payload Claims like user ID, expiration time, roles
Signature Verifies the token is authentic and unchanged

Example:

Header: {"alg": "HS256", "typ": "JWT"}
Payload: {"sub": "1234567890", "name": "John Doe", "exp": 1718291200}
Signature: HMACSHA256(base64UrlEncode(header) + "." + base64UrlEncode(payload))

Summary

  • JWT is a stateless, secure way of handling authentication.
  • It consists of a header, payload, and signature.
  • Good for scalable, distributed systems; not ideal if you need frequent revocation or short sessions.

JWT Signature Explanation: HMACSHA256(base64UrlEncode(header) + "." + base64UrlEncode(payload))

This line describes how the signature part of a JWT (JSON Web Token) is created using the HMAC-SHA256 algorithm.


JWT Structure

A JWT is composed of three parts:

header.payload.signature

1. base64UrlEncode(header)

  • The header is a JSON object, typically like:
    {
      "alg": "HS256",
      "typ": "JWT"
    }
  • It is:
    1. Converted to a string:
      '{"alg":"HS256","typ":"JWT"}'
    2. Encoded using Base64 URL encoding (a safe variant of Base64).
  • Result example:
    eyJhbGciOiAiSFMyNTYiLCAidHlwIjogIkpXVCJ9

2. base64UrlEncode(payload)

  • The payload contains claims, e.g.:
    {
      "sub": "1234567890",
      "name": "John Doe",
      "iat": 1516239022
    }
  • It is Base64 URL-encoded the same way.

3. Concatenation

base64UrlEncode(header) + "." + base64UrlEncode(payload)
  • This forms the signing input, e.g.:
    eyJhbGciOiAiSFMyNTYiLCAidHlwIjogIkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ

4. HMACSHA256(...)

  • The signing input is hashed with HMAC-SHA256 using a secret key:

    Python Example:

    import hmac, hashlib
    
    key = b'your-256-bit-secret'
    message = b'header.payload'
    signature = hmac.new(key, message, hashlib.sha256).digest()
  • The signature is also Base64 URL-encoded.


Final JWT Format

<base64url(header)>.<base64url(payload)>.<base64url(signature)>

Each part is separated by a dot.


Would you like to see a full Python example that creates a JWT?

Interview angle

  • “Why use a JWT over a session?” - stateless verification: any service can validate the signature without a shared session store, which suits distributed systems. The cost is that you can’t revoke one before expiry.
  • “How do you handle revocation then?” - short-lived access tokens with longer refresh tokens, plus a denylist keyed on token id for immediate revocation. Accepting the trade explicitly is better than pretending JWTs are revocable.
  • “What are the classic JWT mistakes?” - not verifying the algorithm (accepting alg: none or an HMAC-signed token where RSA was expected), skipping audience and expiry checks, putting sensitive data in a payload that’s merely base64-encoded, and storing tokens in localStorage.