JWT: What is it? Definition and uses in web security

Last update: 26 September, 2024

The JSON Web Token , commonly known as JWT , is an open standard for the secure transmission of information between parties. It is defined under the RFC 7519 specification and is primarily used in the context of web security to authenticate users and ensure data integrity.

Structure of a JWT

A JWT consists of three Base64Url encoded parts , separated by periods:

  • header: Contains metadata about the token, such as the type and signature algorithm used. For example:
{"alg": "HS256", "typ": "JWT"}
  • Payloads: This section contains claims, which are statements about an entity (usually the user) and additional metadata. For example:
  • {"sub": "1234567890", "name": "John Doe", "admin": true}
  • Signature: It is used to validate the integrity of the token and the authenticity of the issuers. To calculate the signature, the header and the payload, are linked and signed using an algorithm such as HMAC SHA256.
  • For example, the signature is generated from:

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

    Types of claims in a JWT

    Claims are generally divided into three categories :

    Claims registered

    They are a set of predefined claims recommended for use in JWTs. These include:

    • iss: The issuer of the token.
    • under: The subject of the token.
    • aud: The target audience of the token.
    • exp: Token expiration date.
    • nbf: Indicates the time at which the token is valid.

    Public complaints

    Claims can be defined at will by users, but must avoid name collisions. For example:

    • username: Username of the authenticated individual.
    • role: User role (admin, regular user, etc.).

    Private claims

    Custom claims are created to share information between parties in a way that will not interfere with registered or public claims.

    How does a JWT work in web security?

    The workflow of a JWT generally follows these steps:

    Authentication

    The process begins when a user successfully authenticates, usually through a login form. Once the user is verified, the server generates a JWT containing information about the user's session.

    Token Generation

    After authentication, the server creates a JWT and sends it to the client as a response. This token can be stored in localStorage or as a cookie in the browser.

    Sending the Token

    With each subsequent request, the client sends the JWT to the server, usually through the Authorization header :

    Authorization: Bearer 

    Token Verification

    The server receives the token and verifies it using the secret key or certificate. If the token is valid and has not expired, access to the protected resources is granted.

    Advantages of using JWT

    Using JWT in web applications has several advantages:

    Scalability

    JWTs are self -contained, meaning servers don't need to maintain a user session in memory. This improves scalability, as multiple server instances can handle requests without needing to access the database to check session state.

    Interoperability

    As an open standard, JWT is interoperable across different programming languages ​​and platforms. This facilitates integration into various systems and services.

    Security

    The ability to sign the JWT ensures that the content has not been altered, and the use of encryption algorithms adds an additional layer of security, providing confidentiality when required.

    Disadvantages of using JWT

    Despite its advantages, there are also disadvantages to implementing JWT :

    Token Size

    JWTs can become large, especially if they contain a lot of information in the payload . This can lead to increased network overhead if they are sent with every request.

    Expiration and Revocation

    Once issued, a JWT is valid until it expires. If a user needs to be revoked (for example, if their account has been compromised), the server must implement an additional mechanism, such as revocation lists, since the token can continue to be used until it expires.

    Key Management

    The security of a JWT depends on the strength of the key used to sign the token. Keeping this key secure and rotating it regularly is crucial for application security.

    Common Uses of JWT

    JWTs are used in a variety of applications and contexts, including:

    API Authentication

    In applications that use RESTful APIs, JWT is frequently used to authenticate requests. It allows API developers to build an architecture that is both secure and easy to use.

    Authentication between Microservices

    In microservices architectures, JWTs facilitate authentication between services by providing a simple way to verify users without the need to share sessions between services.

    SSO (Single Sign-On)

    Implementing JWT can facilitate the deployment of SSO solutions , allowing users to authenticate once and access multiple applications without needing to log in again.

    Secure Information Sharing

    JWTs are also useful for sharing information between different parties, ensuring the integrity and authenticity of the transmitted data.

    Access control

    JWTs allow for the implementation of fine access controls, as data about roles and permissions can be included directly in the token.

    Implementing JWT in a Project

    Creating a JWT

    To create a JWT, you can use various libraries available in multiple languages ​​such as JavaScript, Python y Java. An example in Node.js using the library jsonwebtoken is

    const jwt = require('jsonwebtoken');
    const token = jwt.sign({ id: user.id }, 'your-256-bit-secret', { expiresIn: '1h' });

    Verifying a JWT

    Verifying a JWT is done similarly, using the same library:

    jwt.verify(token, 'your-256-bit-secret', function(err, decoded) {
      if (err) {
        return console.log('Token inválido');
      }
      console.log(decoded); // { id: 123, i Ss: 'your-issuer', ... }
    });

    Handling Token Expiration

    To handle token expiration, the expiration time (claim exp ) in the payload must be checked before granting access to protected resources. If the token has expired, the user must be redirected to log in again and obtain a new token.

    Use of Middleware

    In many applications, especially in the context of Node.js with Express , middleware is used to centrally handle JWT verification . Here's a basic example:

    const express = require('express');
    const jwt = require('jsonwebtoken');
    const app = express();

    const checkToken = (req, res, next) => {
    const token = req.headers['authorization']?.split(' ')[1];
    if (!token) return res.sendStatus(401); // No autorizado

    jwt.verify(token, 'your-256-bit-secret', (err, decoded) => {
    if (err) return res.sendStatus(403); // Prohibido
    req.user = decoded; // Guardar información del usuario en el request
    next(); // Continuar a la siguiente middleware
    });
    };

    app.get('/protected', checkToken, (req, res) => {
    res.send('Este es un recurso protegido.');
    });

    The JSON Web Token is a powerful tool for managing authentication and authorization in web applications. Its simple structure and ability to be verified and validated facilitate the implementation of secure, scalable, and interoperable systems. However, best practices and proper security management must be considered to maximize its effectiveness.