How to Create and Verify JWTs with Node.js ? - GeeksforGeeks

16 Feb, 2022
In this article, we will see how to create and verify JWT tokens in Node.js.
Good knowledge of JavaScript.
Basic knowledge about  ExpressJs.
Basic knowledge about API Authentication.
Basic knowledge about postman and their uses.
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.
Filename: index.js
Javascript
// Import express for creating API's endpointsconst express = require('express'); // Import jwt for API's endpoints authenticationconst jwt = require('jsonwebtoken'); // Creates an Express application, initiate// express top level functionconst app = express(); // A port for serving API'sconst port = 3000;  // A demo get routeapp.get('/', (req, res) => {    res.json({        route: '/',        authentication: false    });});  // Listen the serverapp.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.
Filename: index.js
Javascript
// A fake 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.
Filename: index.js
Javascript
// Allow json dataapp.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.
Filename: index.js
Javascript
// 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;     // Iterate 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.
Filename: index.js 
Javascript
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.
Filename: index.js
Javascript
// Verify routeapp.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 with 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.
Filename: index.js 
Javascript
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:
Filename: index.js
Javascript
// Import express for creating API's endpointsconst express = require("express"); // Import jwt for API's endpoints authenticationconst jwt = require("jsonwebtoken"); // Creates an Express application, initiate// express top level functionconst app = express(); // A port for serving API'sconst port = 3000; // A fake database objectlet databse = [  {    name: "gfg",    work: "knowledge provider",    password: "abc",  },  {    name: "suryapratap",    work: "technical content writer",    password: "123",  },]; // A demo get routeapp.get("/", (req, res) => {  res.json({    route: "/",    authentication: false,  });}); // Allow json dataapp.use(express.json()); // Login routeapp.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;   // iterate 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 routeapp.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 with error    res.json({      login: false,      data: "error",    });  }}); // Listen the serverapp.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.
singghakshay
gulshankumarar231
simmytarika5
surindertarika1234
sweetyty
anikaseth98
surinderdawra388
adnanirshad158
ruhelaa48
sumitgumber28
JSON
Node.js-Methods
NodeJS-Questions
Picked
Node.js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Express.js express.Router() Function
Mongoose Populate() Method
Express.js req.params Property
Mongoose find() Function
How to connect Node.js with React.js ?
Express.js express.Router() Function
How to set input type date in dd-mm-yyyy format using HTML ?
Differences between Functional Components and Class Components in React
How to create footer to stay at the bottom of a Web page?
Convert a string to an integer in JavaScript