Web Development

Use JSON Web Token To Secure Your RESTful APIs: A Guide

Feb 04, 2020

Vikrant Bhatia

When you first start building applications, there might be a time when you want to authenticate certain users into the app that you have spent so much time building. The usual traditional way is to sendFile(“index.html”) way to send back static HTML or use render(“index”) to render a template markup like ejs and plug, chances are you will use session-based authentication.

But what about when you use API to authenticate the user? Then you need another way. The answer to that other way question is by using jsonwebtokens.

What is JSON Web Token?

JSON web token (JWT) is the open standard that defines a self-contained and compact way for securely transferring information between two separate entities as a JSON object. This information is secure and verified because it is digitally signed. JWTs use an HMAC algorithm to be signed, alternatively, they use a public/private key pair using ECDSA or RSA. Web tokens are great for securing Node.js REST API.

So When Do I Use It?

Here are some scenarios where JSON WebTokens are used ;


This is the most common scenario under which people use JWT. Once a user is logged inside the system, every forthcoming request includes the JWT, this allows the users to gain access to routes, services, and resources that fall within the permissible limit of the token. Single sign-on is also a widely used JWT feature.

All this is because of the small overheads and the ability to be adapted across domains.

Information Exchange

JSON Web Tokens is a leading way to securely transfer information between two parties. This is because JWTs are signed. E.g. By using a private/ Public pair, you have the ability to check and verify the sender. Additionally, you also have the capability to calculate the signature with the help of the header and payload.
You can even verify that the content is not tampered with.

Today we will look at the three steps involved in this process.

  • Installation
  • Configuration
  • Test Run


There is a very simple command that helps you install JSON web token

>> npm install jsonwebtoken


After you have completed the standard installation the need arrives to include the package in js file. Your file name is a variable of your choice and has no repercussions on the end product.
var jwt = require(‘jsonwebtoken');
Once the jwt is changed into a jsonwebtoken variable, you can use it to secure any kind of a web token for a RESTful API

Test Run


This process has the capability to help check, if or not the request that a person gives or received is via a trustworthy and authorized source or not


This is the part of the program that holds the ALGORITHM and TOKEN TYPE.
Decoded Header

         "alg": "HS256",
         "typ": "JWT"


This is the original encrypted data that is included in the payload section
Decoded Data

             "email": "abc@gmail.com",
             "name": "mani"


Verified & Decoded signature

This is the most important part of the JWT token that plays a significant part in securing the encoded token that will help it decide if the data is supposed to be accepted or reject the custom signature.

             base64UrlEncode(header) + "." +
             Your-256-bit-secret (secret_word)


Generating Code For Login

There is a whole process associated with the generation of a token for Login purposes. Here is a basic example of the code used.

              router.post("/login", (req, res, next) => {
               let fetchedUser;
               User.findOne({ email: req.body.email })
                 .then(user => {
                   if (!user) {
                     return res.status(401).json({
                       message: "Auth failed"
                   fetchedUser = user;
                   return bcrypt.compare(req.body.password, user.password);
                 .then(result => {
                   if (!result) {
                     return res.status(401).json({
                       message: "Auth failed"
                   const token = jwt.sign(
                     { email: fetchedUser.email, userId: fetchedUser._id },
                     { expiresIn: "1h" }
                     token: token,
                     expiresIn: 3600
                 .catch(err => {
                   return res.status(401).json({
                     message: "Auth failed"


Checking The Validity Of The Token

You need to check a completely different js file and then add the code given below that will act as the middleware for checking whether or not the token is valid.

                const jwt = require("jsonwebtoken");
                module.exports = (req, res, next) => {
                 try {
                   const token = req.headers.authorization.split(" ")[1];
                   jwt.verify(token, "secret_word");
                 } catch (error) {
                   res.status(401).json({ message: "Auth failed!" });


When you are using this method remember if you try and complete this without the help of a token you will fail.Given above is the basic is the most basic way to generate and validate the most secure of the JSON web tokens to secure the while Node.js RESTful API.

Vikrant Bhatia