Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

How to Create and Verify JWTs with Node.js ?

  • Difficulty Level : Basic
  • Last Updated : 01 Nov, 2021

In this article, we will see how to create and verify JWT tokens in Node.js.

Prerequisites:

In web development, we also want to secure our route so we have 3 types of ways to secure our route they are cookies, session, or API authentication. The cookies and session only work with the browser if you want secure routes in the API’s endpoints. So you must need API’s authentication mechanism. Or in the present time, we mostly work with API’s so it is essential to make secure API endpoints. The most popular way in API’s authentication is the use of JsonWebToken, the work with many types of technologies as well as NodeJs also. In this article, we have created some dummy API endpoints with the help of ExpressJs and make their routes secure with the help of the JWT token mechanism and understand how they work and verify the tokens. The abbreviation for JsonWebtoken is JWT.

Approach: Before starting the article we will discuss here the problem details of the article, we are talking about the most popular method to secure API endpoints. Which JWT provides. We will first set up NodeJs to write our code, then we will see how to create and verify the JWT token, finally, we will see the output of our API with the help of the Postman API Testing Tool.

 



Step by step implementation:

Step 1:Firstly set up the NodeJs project.If you do not have NodeJs or NPM please refer to this article. Initiate NodeJs project with npm.

npm init -y

“-y” to mark all question answers as default.

After initiating the NodeJs project move to the second step.

Step 2: After initiating the project install some dependencies. Install express, and jsonwebtoken through npm

npm install express jsonwebtoken

 



Step 3: Install nodemon as a dev-dependency.

npm install -d nodemon

Project Structure: After the installation is complete, create an index.js file and now your directory structure looks like this.

Step 4: Add one more script in the package.json file. Open the package.json file and add one line below to the test script.

Step 5: Before create and verify the API endpoint with the help of JWT, and express firstly write some code for further use.

index.js




// Import express for creating API's endpoints
const express = require('express');
  
// Import jwt for API's endpionts authentication
const jwt = require('jsonwebtoken');
  
// Creates an Express application, initiate
// express top level function
const app = express();
  
// A port for serving API's
const port = 3000;
  
  
// A demo get route
app.get('/', (req, res) => {
    res.json({
        route: '/',
        authentication: false
    });
});
  
  
// Listen the server
app.listen(port, () => {
    console.log(`Server is running : http://localhost:${port}/`);
});

 



Step 6: After the dummy code is ready, then create a json database object and store some dummy data.

index.js




// A faek database object.
let databse = [
    {
        name: 'gfg',
        work: 'knowledge provider',
        password: 'abc'
    },
    {
        name: 'suryapratap',
        work: 'technical content writer',
        password: '123'
    }
];

Step 7: Allow JSON data to make communicate with API. Allow the JSON data in a request by adding middleware for the body parser.

index.js




// Allow json data
app.use(express.json());

Step 8: Create a login route and create a JWT token. Here, create a login post route and create a JWT token and return it to the response., read code comments for better understanding.

index.js




// Login route.
app.post('/login', (req, res) => {
  
    // Get the name to the json body data
    const name = req.body.name;
  
    // Get the password to the json body data
    const password = req.body.password;
  
    // Make two variable for further use
    let isPresent = false;
    let isPresnetIndex = null;
  
    // Itarate a loop to the data items and
    // check what data are method
    for(let i=0; i<databse.length; i++){
  
        // If data name are matched so check
        // the password are correct or not
        if(databse[i].name === name && 
        databse[i].password === password){
  
            // If both are correct so make 
            // isPresent variable true
            isPresent = true;
  
            // And store the data index
            isPresnetIndex = i;
  
            // Break the loop after matching
            // successfully
            break;
        }
    }
  
    // If isPresent is true, then create a
    // token and pass to the response
    if(isPresent){
  
        // The jwt.sign method are used
        // to create token
        const token = jwt.sign(
            databse[isPresnetIndex],
            'secret'
        );
          
        // Pass the data or token in response
        res.json({
            login: true,
            token: token,
            data: databse[isPresnetIndex]
        });
    }else{
  
        // If isPresent is false return the error
        res.json({
            login: false,
            error: 'please check name and password.'
        });
    }
});

Step 9: JWT sign method is used to creating a token the take are three arguments one is a response object, and the second one is a secret key and the last one is an options object for better use of the token.

index.js




jwt.sign(
    {data_obeject},
    "secret_key",
    {Options}
)

If you want more about the jwt.sign method refer to the official documentation. 

Step 10: Now we will make another route for authentication jwt token. Here, we create an authentication route and authenticate the coming JWT token.



index.js




// Verify route
app.get('/auth', (req, res) => {
  
    // Get token value to the json body
    const token = req.body.token;
  
    // If the token is present
    if(token){
  
        // Verify the token using jwt.verify method
        const decode = jwt.verify(token, 'secret');
  
        //  Return response with decode data
        res.json({
            login: true,
            data: decode
        });
    }else{
  
        // Return response weith error
        res.json({
            login: false,
            data: 'error'
        });
    }
});

Step 11: JWT verify method is used for verify the token the take two arguments one is token string value, and second one is secret key for matching the token is valid or not. The validation method returns a decode object that we stored the token in.

index.js




jwt.verify(token_value, 'secret_key');

If you want more about the jwt.verify method refer to the official documentation.

Below is the complete code of the above step by step implementation:

index.js




// Import express for creating API's endpoints
const express = require("express");
  
// Import jwt for API's endpionts authentication
const jwt = require("jsonwebtoken");
  
// Creates an Express application, initiate
// express top level function
const app = express();
  
// A port for serving API's
const port = 3000;
  
// A faek database object
let databse = [
  {
    name: "gfg",
    work: "knowledge provider",
    password: "abc",
  },
  {
    name: "suryapratap",
    work: "technical content writer",
    password: "123",
  },
];
  
// A demo get route
app.get("/", (req, res) => {
  res.json({
    route: "/",
    authentication: false,
  });
});
  
// Allow json data
app.use(express.json());
  
// Login route
app.post("/login", (req, res) => {
  
  // Get the name to the json body data
  const name = req.body.name;
  
  // Get the password to the json body data
  const password = req.body.password;
  
  // Make two variable for further use
  let isPresent = false;
  let isPresnetIndex = null;
  
  // Itarate a loop to the data items and
  // check what data are matched.
  for (let i = 0; i < databse.length; i++) {
  
    // If data name are matched so check
    // the password are correct or not
    if (databse[i].name === name 
      && databse[i].password === password) {
  
      // If both are correct so make 
      // isPresent variable true
      isPresent = true;
  
      // And store the data index
      isPresnetIndex = i;
  
      // Break the loop after matching successfully
      break;
    }
  }
  
  // If isPresent is true, then create a
  // token and pass to the response
  if (isPresent) {
  
    // The jwt.sign method are used
    // to create token
    const token = jwt.sign(databse[isPresnetIndex], "secret");
  
    // Pass the data or token in response
    res.json({
      login: true,
      token: token,
      data: databse[isPresnetIndex],
    });
  } else {
  
    // If isPresent is false return the error
    res.json({
      login: false,
      error: "please check name and password.",
    });
  }
});
  
// Verify route
app.get("/auth", (req, res) => {
  
  // Get token value to the json body
  const token = req.body.token;
  
  // If the token is present
  if (token) {
  
    // Verify the token using jwt.verify method
    const decode = jwt.verify(token, "secret");
  
    //  Return response with decode data
    res.json({
      login: true,
      data: decode,
    });
  } else {
  
    // Return response weith error
    res.json({
      login: false,
      data: "error",
    });
  }
});
  
// Listen the server
app.listen(port, () => {
  console.log(`Server is running : 
    http://localhost:${port}/`);
});

Step to test the routes: We will use Postman to test the API routes. Firstly test the login route. Open the postman and make a post request on the ‘/login’ route with appropriate JSON data.

Use the localhost address and make a post request in /login route and send the appropriate data in json format and finally, you get a JSON response with login status and the token or data of the object. Use the token to authentication of the API endpoints and again use the localhost address and make a get request in ‘/auth’ route and send the appropriate data token.

After validation, you will get the proper data object store in the token.




My Personal Notes arrow_drop_up
Recommended Articles
Page :