Principles and Implementation of JWT (JSON Web Token)

Principles and Implementation of JWT (JSON Web Token)

I. What is JWT?
JWT is an open standard (RFC 7519) for securely transmitting claims (such as user identity information) between web applications. It consists of three parts: Header, Payload, and Signature, connected by dots to form a string, for example:
xxxxx.yyyyy.zzzzz

II. Detailed Structure of JWT

  1. Header

    • Purpose: Specifies the token type and signing algorithm (e.g., HMAC SHA256 or RSA).
    • Example:
      {
        "alg": "HS256",  // Algorithm type
        "typ": "JWT"     // Token type
      }
      
    • Processing: The JSON object is encoded with Base64Url to form the first part.
  2. Payload

    • Purpose: Carries the actual claims to be transmitted (e.g., user ID, permission roles).
    • Claim Types:
      • Registered Claims (standard fields, such as exp expiration time, iss issuer).
      • Public Claims (can be customized but should avoid conflicts).
      • Private Claims (business-defined fields, such as userId).
    • Example:
      {
        "sub": "1234567890",
        "name": "John Doe",
        "admin": true,
        "iat": 1516239022  // Issued at time
      }
      
    • Processing: Also encoded with Base64Url to form the second part.
  3. Signature

    • Purpose: Prevents data tampering and verifies message integrity.
    • Generation Method:
      HMACSHA256(
        base64UrlEncode(header) + "." + base64UrlEncode(payload),
        secret_key
      )
      
    • Key Point: The signature must be generated using a secret key saved on the server (or a private key for asymmetric encryption), which cannot be forged by the client.

III. JWT Workflow

  1. Login Authentication

    • The user submits credentials (e.g., username/password) to the server.
    • After successful verification, the server generates a JWT and returns it to the client (usually stored in a Cookie or LocalStorage).
  2. Subsequent Request Verification

    • The client includes the JWT in the request header (e.g., Authorization: Bearer <token>).
    • The server verifies whether the signature is valid and if the token has expired (by checking the exp field).
    • After successful verification, the server directly uses the information in the payload to process the business logic without querying the database.

IV. Advantages and Risks of JWT

  1. Advantages

    • Stateless: The server does not need to store session information, making it suitable for distributed systems.
    • Extensible: The payload can include custom business fields, reducing database queries.
  2. Risks and Considerations

    • Once a token is issued, it cannot be forcibly invalidated before expiration (requires mitigation through blacklisting or short expiration periods).
    • Sensitive information should not be stored in plain text in the payload (as Base64 is decodable; encryption is required).
    • Key leakage can lead to token forgery, so the key must be strictly protected.

V. Code Implementation Example (Node.js)

const jwt = require('jsonwebtoken');

// Generate JWT
const token = jwt.sign(
  { userId: 123, role: 'admin' },
  'your-secret-key',
  { expiresIn: '1h' }  // Expiration time
);

// Verify JWT
jwt.verify(token, 'your-secret-key', (err, decoded) => {
  if (err) throw new Error('Invalid token');
  console.log(decoded.userId); // Output: 123
});

VI. Summary
JWT ensures data integrity through its signature mechanism and is suitable for stateless authentication scenarios. However, attention must be paid to security practices such as key management and expiration settings. Based on specific business requirements, it can be extended to patterns like Refresh Tokens to enhance security.