• 1 year ago

Understanding JWT (JSON Web Token)

In today’s web development landscape, security and authentication are paramount. One popular method for securely transmitting information between parties is through JWT (JSON Web Token). It's compact, self-contained, and widely used for stateless authentication in modern applications, especially with REST APIs.

What is a JWT Token?

JWT (JSON Web Token) is an open standard (RFC 7519) that defines a compact and self-contained way for securely transmitting information as a JSON object between parties. This information can be verified and trusted because it is digitally signed.

πŸ” Structure of a JWT

A JWT has three parts, separated by dots (.):

xxxxx.yyyyy.zzzzz

  1. Header: Contains metadata like type and signing algorithm.

  2. Payload: Contains the claims (user data, metadata, etc.).

  3. Signature: Used to verify the token's integrity.

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

// Payload
{
  "userId": 123,
  "username": "devsingh",
  "role": "admin",
  "exp": 1712345678
}

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

How JWT Works

  1. βœ… User Logs In
    User provides credentials. If correct, the server generates a JWT and sends it back.

  2. πŸ” Client Stores Token
    The JWT is stored on the client-side (usually in localStorage or sessionStorage).

  3. πŸ“² Send Token with Requests
    The client sends the token in the Authorization header:

Authorization: Bearer <token>

πŸ” Server Verifies Token
The server verifies the token signature and checks expiry before granting access.

🚫 Common Mistakes to Avoid

  • ❌ Never store JWT in cookies without HttpOnly and Secure flags.

  • ❌ Never expose secret keys to the frontend.

  • β›” Avoid putting sensitive data like passwords inside the JWT payload.


πŸ›‘οΈ Refresh Tokens

JWTs are usually short-lived (e.g., 15 minutes). For persistent login:

  • Issue a refresh token (longer expiry).

  • On JWT expiry, use refresh token to get a new JWT.

  • Store refresh token securely, preferably in HttpOnly cookies.

πŸ“¦ Libraries & Tools

  • Node.js: jsonwebtoken

  • Python: PyJWT

  • Java: jjwt, auth0-java

  • .NET: System.IdentityModel.Tokens.Jwt

  • Laravel: tymon/jwt-auth  

πŸ”— https://jwt.io — Visual debugger and documentation

πŸ“˜ RFC 7519: JSON Web Token (JWT)