DEV Community

Softden 2005
Softden 2005

Posted on • Edited on

🌟 Complete JSON Web Token (JWT) Guide

JSON Web Tokens (JWT) are a popular way to securely transmit information between parties as a JSON object. They are compact, self-contained, and can be used for authentication, information exchange, or user authorization. Let’s break down JWT step by step with examples!


πŸ“š What is JWT?

JSON Web Token (JWT) is a compact and URL-safe token that represents claims securely between two parties. A typical JWT is composed of three parts:

  1. Header: Metadata about the token (algorithm, token type)
  2. Payload: Claims or data
  3. Signature: A cryptographic signature to verify integrity

πŸ› οΈ How does JWT work?

The JWT works by allowing the server to sign the token using a secret key or public/private key pair. When the client receives the token, they store it and use it to authenticate further requests without needing to transmit the user’s credentials again.

Token Structure:

xxxxx.yyyyy.zzzzz
Enter fullscreen mode Exit fullscreen mode
  • Header: Encoded using Base64Url
  • Payload: Encoded using Base64Url
  • Signature: Ensures the data hasn’t been tampered with

🧩 Components of JWT

  1. ### Header 🏷️ The header contains metadata about the type of token and the algorithm used for signing the token.

Example:

   {
     "alg": "HS256",
     "typ": "JWT"
   }
Enter fullscreen mode Exit fullscreen mode
  1. ### Payload πŸ“¨ This is where the claims (data) are stored. Common claim types include:
  • Registered Claims: Standard claims such as iss (issuer), exp (expiration), sub (subject), etc.
  • Public Claims: Custom claims defined by users.
  • Private Claims: Non-standard claims agreed upon between two parties.

Example:

   {
     "sub": "1234567890",
     "name": "John Doe",
     "admin": true,
     "iat": 1516239022
   }
Enter fullscreen mode Exit fullscreen mode
  1. ### Signature πŸ” To create the signature, we:
  • Encode the header and payload using Base64Url
  • Use a secret or private key to hash the encoded data (header & payload)
  • Concatenate the result

Example in JavaScript:

   const encodedHeaderPayload = base64UrlEncode(header) + '.' + base64UrlEncode(payload);
   const signature = HMACSHA256(encodedHeaderPayload, 'your-secret-key');
Enter fullscreen mode Exit fullscreen mode

The final JWT looks like this:

   xxxxx.yyyyy.zzzzz
Enter fullscreen mode Exit fullscreen mode

βš™οΈ How to Use JWT in Applications

  1. ### Authentication πŸ›‚ JWT is commonly used in authentication systems. After a user logs in successfully, the server generates a JWT and sends it to the client. The client then includes the JWT in every subsequent request to prove their identity.

Example (Using in HTTP headers):

   Authorization: Bearer <JWT Token>
Enter fullscreen mode Exit fullscreen mode
  1. Authorization πŸ”

    Once a user is authenticated, JWT can be used to verify the roles or permissions of the user for accessing certain parts of the application.

  2. Information Exchange πŸ”„

    JWT can also be used to securely transmit information between parties, ensuring that the message hasn’t been tampered with.


✍️ Example: Creating and Validating JWT in Node.js

  1. Install JWT library
   npm install jsonwebtoken
Enter fullscreen mode Exit fullscreen mode
  1. Generating a Token
   const jwt = require('jsonwebtoken');

   const payload = { userId: 123, username: "john_doe" };
   const secret = "mySuperSecretKey";

   const token = jwt.sign(payload, secret, { expiresIn: '1h' });
   console.log("Generated Token:", token);
Enter fullscreen mode Exit fullscreen mode
  1. Verifying a Token
   const decoded = jwt.verify(token, secret);
   console.log("Decoded Payload:", decoded);
Enter fullscreen mode Exit fullscreen mode

πŸ”‘ Key Points to Remember

  1. Compact & Self-contained: JWT tokens are compact and can store all necessary information (claims) for authentication and authorization.

  2. Security: Ensure that your secret key is kept safe. Use strong encryption (like RS256) for enhanced security.

  3. Expiration: Always set an expiration time (exp) to avoid prolonged access if the token is stolen.

  4. Stateless: JWT allows for stateless authentication. You don't need to store session data on the server, reducing the load.


🚨 Common JWT Vulnerabilities and Best Practices

  1. Weak Signing Algorithm: Don’t use weak algorithms like none. Stick with secure algorithms like HS256 or RS256.

  2. Expired Tokens: Ensure that tokens expire within a reasonable period (exp claim). Don’t make the expiration too long.

  3. Storing Tokens: Always store JWT securely (e.g., in httpOnly cookies or secure storage). Don’t store them in localStorage unless absolutely necessary.


πŸ”„ JWT Refresh Tokens

A Refresh Token is used to obtain a new access token when the old one expires. A good practice is to issue two tokens:

  • Access Token: Short-lived, used for immediate access.
  • Refresh Token: Long-lived, used to request a new access token.

πŸ—“οΈ Conclusion

  • What: JSON Web Token (JWT) is a compact and URL-safe way to transmit data between two parties.
  • Why: Used for authentication, authorization, and securely transmitting information.
  • How: JWT has a structure of three parts: Header, Payload, and Signature. It's generated using a secret or public/private key pair.
  • When: JWT is commonly used in web applications for secure user authentication and data exchange.

By following this guide, you can implement and understand how to use JWT securely and effectively in your applications!

Top comments (0)