Skip to content

JWT: Definition and Use Cases

TL;DR:

JWT (JSON Web Token) is a compact cryptographic token consisting of three base64 parts separated by dots: header.payload.signature. It contains claims (user_id, roles, exp) signed with HMAC or RSA. Used for stateless authentication in APIs. Any client can read it without contacting the server, but only a secret can verify it.

Check your site →

What is JWT

JWT (JSON Web Token) is a compact cryptographic token consisting of three base64 parts separated by dots: header.payload.signature. It contains claims (user_id, roles, exp) signed with HMAC or RSA. Used for stateless authentication in APIs. Any client can read it without contacting the server, but only a secret can verify it.

Check JWT online

Open Enterno.io tool →

Understanding the Structure of JWT

JSON Web Tokens (JWT) are composed of three parts: Header, Payload, and Signature. Each part is encoded in Base64Url format and separated by dots.

1. 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. This can be represented in JSON format as follows:

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

After Base64Url encoding, it becomes a string that will form the first part of the JWT.

2. Payload: The payload contains the claims. Claims are statements about the entity (typically, the user) and additional data. There are three types of claims: registered, public, and private claims. An example payload might look like this:

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

After Base64Url encoding, this forms the second part of the JWT.

3. Signature: To create the signature part, you must take the encoded header, the encoded payload, a secret, and the algorithm specified in the header. For example, using HMAC SHA256, the signature would be created like this:

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

This signature allows the recipient to verify that the sender of the JWT is who it claims to be and to ensure that the message wasn't changed along the way.

JWT Authentication Flow: A Step-by-Step Guide

The JWT authentication flow involves several key steps that facilitate secure communication between a client and a server. Here’s a breakdown of the process:

  1. User Login: The user provides their credentials (username and password) to the server.
  2. Token Generation: If the credentials are valid, the server generates a JWT, which includes user information and claims, and sends it back to the client.
  3. Token Storage: The client stores the JWT in local storage or session storage. This token will be sent with every subsequent request to authenticate the user.
  4. Accessing Protected Resources: When the client makes a request to access a protected resource, it includes the JWT in the Authorization header:
Authorization: Bearer 

  • Token Verification: The server receives the request, extracts the JWT from the Authorization header, and verifies the token's signature using the secret key. If the verification is successful, the server processes the request.
  • Response: The server responds with the requested resource or an error message if the token is invalid or expired.
  • This flow ensures that sensitive data is only accessible to authenticated users, while the stateless nature of JWT allows for scalability since the server does not need to store session information.

    Practical Example: Implementing JWT in a Node.js Application

    Implementing JWT in a Node.js application involves several straightforward steps. Below is a practical example demonstrating how to add JWT-based authentication to a simple Node.js application:

    1. Install Required Packages: First, ensure you have Node.js installed, then create a new project and install the required packages:

    npm init -y
    npm install express jsonwebtoken body-parser

    2. Set Up the Server: Create a file named server.js and set up a basic Express server:

    const express = require('express');
    const jwt = require('jsonwebtoken');
    const bodyParser = require('body-parser');
    const app = express();
    app.use(bodyParser.json());

    3. Create a Login Route: Add a route for user login that generates a JWT:

    app.post('/login', (req, res) => {
    // Validate user credentials
    const user = { id: 1, username: req.body.username };
    const token = jwt.sign({ user }, 'your_secret_key');
    res.json({ token });
    });

    4. Protect Routes: Create a middleware function to verify the JWT:

    function authenticateToken(req, res, next) {
    const token = req.headers['authorization']?.split(' ')[1];
    if (!token) return res.sendStatus(401);
    jwt.verify(token, 'your_secret_key', (err, user) => {
    if (err) return res.sendStatus(403);
    req.user = user;
    next();
    });
    }

    5. Add Protected Routes: Use the middleware to protect routes:

    app.get('/protected', authenticateToken, (req, res) => {
    res.send('This is a protected route!');
    });

    6. Start the Server: Finally, start the server:

    app.listen(3000, () => {
    console.log('Server running on port 3000');
    });

    This example illustrates how straightforward it is to implement JWT authentication in a Node.js application, allowing you to secure your API endpoints efficiently.

    Learn more

    Frequently Asked Questions

    Do I need JWT?

    If you work with web infrastructure or APIs, almost certainly yes. See the article above for specific use cases.

    Try the live tool that powered this guide

    Free plan — 10 monitors, checks every 5 min, no card required. Upgrade for 1-minute interval and multi-region monitoring.