Articles

What is a JSON Web Token?

Apr 14 6 min read node
jwtweb-tokennode

JSON Web Token is a self-contained and compact way for transmitting pieces of information between parties securing as a JSON object. Information is digitally signed so it can be verified. For digital signing, a secret (with the HMAC algorithm) or a public/private key pair using RSA or ECDSA.

One common use case for JWT is for client authorization. Once a user is logged in the server checks the user's credentials and sends a response, including a JSON web token, signed by the server's secret key. Upon logging in, each request from the user will contain the JWT sent by the server. This helps the server validate that the user is the same user who logged in and is authorized to access resources/services.

Another good use of JSON web token is data transmission among different parties. As the tokens are signed with a secret key, the payload can be verified if it was tampered.

Structure of JSON Web token

JSON Web Tokens are divided into three parts and separated by a dot (.)

  1. Header : The header contains information about what algorithm is being used and also the type of the token being used, in this case it's JWT.
JSON Web Tokens
{
"alg": "HS256",
"typ": "JWT",
}
  1. Payload: The payload portion contains the users' information and some additional information to verify/identify the user and grant access to specific resources. It is also a good practice to expire your tokens so that someone else can't use your token to gain access. For this, token expire information can also be added within the payload.
Sample Payload
{
  "_id": "6574765161",
  "name": "Jackie Chan",
  "iat": "1516239022",
  "exp": "1615673602"
}
  1. Signature: Lastly, the signature part is a combination of three Base64-URL strings that are separated by dots. This can be easily passed while being more compact when compared to XML-based standards such as SAML and can later be verified.
Signature Structure
HMACSHA256(base64UrlEncode(header) + "." + base64UrlEncode(payload), "json-web-token-following");

The token structure looks something like: header.payload.signature The token itself :

JWT token
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJfaWQiOiI2NTc0NzY1MTYxIiwibmFtZSI6IkphY2tpZSBDaGFuIiwiaWF0IjoiMTUxNjIzOTAyMiIsImV4cCI6IjE2MTU2NzM2MDIifQ._ar1JLdQErmVNSyqVjMW8FolQwlkhADNyEFjMgiEgCM

Example of JSON Web tokens

For this example, I'm using my project, which already includes user login and registration functionality. So I will be explaining how to verify JWT tokens and protect routes using tokens.

You can find the project from Github

  # clone repo
  git clone https://github.com/ratul16/node-express-auth-registration.git

  # navigate to directorycd node-express-auth-registration
  cd node-express-auth-registration

Create a .env file and store your MongoDB url and secret key and your are good to go.

MONGODB = "mongodb-url"
TOKEN_SECRET = "your-secret-key"

Finally

# install dependencies
$ npm install

# serve with hot reload at localhost:3000
$ npm start

As discussed above, each request from the user has to contain the JSON web token to have access to resources. Here will demonstrate a similar scenario, if the request header doesn't contain a valid token, then the user's access will be denied.

In the auth function, we check if the request header contains the token. If not, we send a response with a status code 401, which means access is denied. But if the token exists in the request header, then we are verifying it within the try-catch. jsonwebtoken has a built-in function for token verification, which requires the token and secret key as shown below. If it's an invalid token, we will send a response with status code 400; else, we are returning the token as verified.

tokenVerify.js
const JWT = require('jsonwebtoken');

function auth(req, res, next) {
  const token = req.header('auth-header');

// checking if token exists or not if (!token)
return res.send({
      statusCode: 401,
      message: "Access Denied"
  });

token verification {
try {
      const verified = JWT.verify(token, process.env.TOKEN_SECRET);
      req.user = verified;
      next();
  } catch (error) {
      res.send({
          statusCode: 400,
          message: "Invalid Token"
      });
  }
}

module.exports = auth;

Now in the post route, we need to import tokenVerify.js script and pass it as a parameter. A try-catch will check if it is verified.

post.js
// Post Route
const router = require("express").Router();
const postSchema = require("../models/Post");
const verify = require("./tokenVerify");

router.get("/", verify, async (req, res) => {
  try {
    const posts = await postSchema.find();
    res.send(posts);
  } catch (err) {
    res.send({ message: err });
  }
});

Now lets test it out!

I am using postman to test the API, and you can use the tool your comfortable with. After setting up the project and registering a user. Now login with the user's email and password. If everything goes well, you will see a response like this.

{
    "statusCode": 200,
    "message": "Logged In !!"
}

And now, if you check the header, you will see the auth-token key with the token value. Now you can store and use this token to the sent request.

Now that we have the token, let try requesting some data. We need to include the token in the header as auth-header and send the request. After that, we will see all the posts that are stored in the database.

But if the token has tampered with, then the request will be invalid and get a response.

{
    "statusCode": 400,
    "message": "Invalid Token"
}

Thank You

All rights reserved.
Hasib • © 2026