EN ES
Home > Web development > What is JWT on the web and how to use it?

What is JWT on the web and how to use it?

Diego Cortés
Diego Cortés
October 1, 2024
What is JWT on the web and how to use it?

JSON Web Token (JWT) is an open standard (RFC 7519) that allows the secure transmission of information between different parties as a JSON object. This information can be verified and trusted for its authenticity, as it is digitally signed. In this article, we will explore what JWT is, how it works, and how to implement it in web applications.

What is JWT?

Definition of JWT

JWT is a method of representing information in a secure and compact format that can be transmitted via URLs, POST, or AJAX. It is commonly used for user authentication and authorization in web applications.

Components of a JWT

A JWT consists of three parts:

  1. Header
  2. Payload
  3. Signature

Header

The header typically consists of two parts: the type of token, which is JWT, and the signing algorithm being used, such as HMAC SHA256 or RSA.

Example of a Header in JSON format:

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

Payload

The payload contains the claims about a user and other data. The claims can be registered, public, or private.

Example of a Payload:

{
  "sub": "1234567890",
  "name": "John Doe",
  "iat": 1516239022
}

Signature

To create the signature, the encoded header and the encoded payload are taken and combined with a secret key using the algorithm specified in the header.

Example of the signature:

HMACSHA256(
  base64UrlEncode(header) + "." +
  base64UrlEncode(payload),
  your-256-bit-secret)

How does JWT work?

JWT works in a simple flow:

  1. Authentication: When a user logs in, the server generates a JWT and sends it to the client.
  2. Storage: The client stores the token (typically in localStorage or cookies).
  3. Access to protected resources: The client sends the JWT in the authorization header on subsequent requests.
  4. Validation: The server validates the token and grants access to protected resources.

Example of authentication flow with JWT

  1. The user sends their credentials (username and password) to the server.
  2. The server validates the credentials, and if they are correct, it generates a JWT.
  3. The server sends the JWT to the client.
  4. The client stores the JWT and includes it in subsequent requests.
  5. The server verifies the JWT and grants access to secure resources.

Advantages of using JWT

  1. Compact: Due to its small size, JWT is ideal for being sent through HTTP headers.
  2. Self-contained: It contains all the necessary information about the user, reducing the need to query the database.
  3. Security: Tokens can be signed and encrypted, providing a higher level of security.

Disadvantages of using JWT

  1. Token size: Although compact, the size of a JWT can increase if many claims are added.
  2. Complex revocation: Since tokens are self-contained, revoking a token before its expiry can be complicated.
  3. Stateless: While JWTs can be used to store session information, this can be an issue if constant information is required or if each session needs to be changed.

How to use JWT in web applications

Step 1: Install dependencies

If you are using Node.js, you may want to use the jsonwebtoken package. You can install it using npm:

npm install jsonwebtoken

Step 2: Create a token

When a user logs in successfully, you can generate a JWT:

const jwt = require('jsonwebtoken');

const user = {
  id: 1,
  name: 'John Doe'
};

// Sign the token
const token = jwt.sign(user, 'secretkey', { expiresIn: '1h' });
console.log(token);

Step 3: Verify the token

Whenever you receive a token from the client, it's important to verify it to ensure it is valid:

jwt.verify(token, 'secretkey', (err, decoded) => {
  if (err) {
    return res.sendStatus(403); // Forbidden
  }
  console.log(decoded); // Decoded user information
});

Step 4: Set up middleware

You can create middleware to authenticate using JWT on your server:

function authenticateToken(req, res, next) {
  const token = req.header('Authorization').split(' ')[1];

  if (!token) return res.sendStatus(401);

  jwt.verify(token, 'secretkey', (err, user) => {
    if (err) return res.sendStatus(403);
    req.user = user;
    next();
  });
}

Conclusion

JWT is a powerful tool for authentication and authorization in web applications. By allowing the secure transmission of information, JWT has become a preferred standard in many modern applications. While it has its advantages and disadvantages, understanding how to implement it correctly can significantly enhance the security and efficiency of your web application.

Diego Cortés
Diego Cortés
Full Stack Developer, SEO Specialist with Expertise in Laravel & Vue.js and 3D Generalist

Categories

Page loaded in 24.53 ms