JWT (JSON Web Token) is a compact, secure way to transmit information between two parties — usually a client (like a browser or mobile app) and a server — as a JSON object. It’s commonly used for authentication and authorizationin web applications.

Structure of a JWT

Codeflare

A JWT is made up of three parts, separated by dots (.):

xxxxx.yyyyy.zzzzz
  • Header
  • Payload
  • Signature

1. Header

The header contains metadata about the token, like the type (JWT) and the algorithm used for signing (e.g., HS256).

Example:

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

This is then Base64Url-encoded to form the first part of the token.

2. Payload

The payload contains the actual data (claims) you want to transmit, such as user info or token expiry time.

Example:

{
  "sub": "1234567890",
  "name": "John Doe",
  "admin": true,
  "exp": 1739700000
}

Types of claims:

  • Registered claims: predefined fields like iss (issuer), exp (expiration), sub (subject), aud (audience).
  • Public claims: custom data, e.g., name, role.
  • Private claims: application-specific data shared between two parties.

This part is also Base64Url-encoded.

3. Signature

To ensure the token wasn’t tampered with, the server signs it using a secret key (or a private key in asymmetric cryptography).

For example:

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

The output is encoded again, forming the third part of the token.

Example JWT

eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.
eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiYWRtaW4iOnRydWV9.
TJVA95OrM7E2cBab30RMHrHDcEfxjoYZgeFONFh7HgQ

How JWT Works (Authentication Flow)

  1. User logs in → The server validates credentials.
  2. Server creates a JWT → Signs it using a secret key.
  3. Server sends the token to the client.
  4. Client stores the token (usually in localStorage or cookies).
  5. For each request, the client sends the token in the Authorization header:
Authorization: Bearer <token>

6. Server verifies the token → If valid, grants access to protected routes/resources.

Advantages

  • Stateless: No need to store sessions on the server.
  • Compact: Easy to transmit in URLs, headers, or cookies.
  • Cross-platform: Works with any language that supports JSON.

Disadvantages

  • Cannot be revoked easily: Once issued, a JWT is valid until it expires.
  • Larger than traditional session IDs.
  • Sensitive data must never be stored inside the payload (even though it’s encoded, it’s not encrypted).

Example in Node.js

Using jsonwebtoken package:

const jwt = require('jsonwebtoken');

// Generate a token
const token = jwt.sign({ userId: 123, role: 'admin' }, 'secretkey', { expiresIn: '1h' });

// Verify a token
try {
  const decoded = jwt.verify(token, 'secretkey');
  console.log(decoded);
} catch (err) {
  console.error('Invalid token');
}

Recent Posts

CRUD Operations: The Foundation of Data Management

Every application that stores and manages data relies on a set of basic operations known…

1 week ago

Common PHP Mistakes Every Developer Should Avoid

PHP remains one of the most widely used server-side programming languages, powering platforms such as…

1 week ago

Danfo.js: The JavaScript Data Science Library

Danfo.js is an open-source JavaScript library designed for data manipulation, analysis, and machine learning. It provides…

1 week ago

Common Async/Await Mistakes Every JavaScript Developer Should Avoid

JavaScript's async and await keywords revolutionized asynchronous programming by making asynchronous code look and behave more like synchronous code.…

1 week ago

PGP Encryption And How It Works

Pretty Good Privacy (PGP) is one of the most widely used encryption systems for securing emails,…

2 weeks ago

How To Migrate from PostgreSQL to MySQL

Database migration is one of the most challenging tasks in software engineering. While both PostgreSQL…

3 weeks ago