JWT Authentication with Node.js

07 Oct, 2021
JSON Web Token is an open standard for securely transferring data within parties using a JSON object. JWT is used for stateless authentication mechanisms for users and providers, this means maintaining session is on the client-side instead of storing sessions on the server. Here, we will implement the JWT authentication system in NodeJs.
Modules Required:
NodeJs: NodeJs for backend
dotenv: For handling configuration data
npm install dotenv
ExpressJS: ExpressJS for Handling routes.
jsonwebtoken module:
npm install jsonwebtoken
All Steps:Create our project:To create a Node project, npm init -y is used in the folder in which the user wants to create a project. The npm command line will ask a number of questions like name, license, scripts, description, author, keywords, version, main file, etc. After npm is done creating the project, a package.json file will be visible in the project folder as proof that the project has been initialized.npm init -yInstall modulesAfter creating the project, next step is to incorporate the packages and modules to be used in the Node Project. To install packages and modules in the project use the following syntax:npm install express dotenv jsonwebtokenCreate our ServerImporting all the dependencies and creating a server using express.jsJavascriptJavascriptconst express = require('express');const dotenv = require('dotenv');const jwt = require('jsonwebtoken');  const app = express();  // Set up Global configuration accessdotenv.config();  let PORT = process.env.PORT || 5000;app.listen(PORT, () => {  console.log(`Server is up and running on ${PORT} ...`);});Create Configuration File (.env)This files contains those variables that we need to pass to our application’s environment.JavascriptJavascriptPORT = 5000  JWT_SECRET_KEY = gfg_jwt_secret_key  TOKEN_HEADER_KEY = gfg_token_header_keyCreate Route for Generating JWTCreating a ‘post’ request that sends the JWT token in the response.JavascriptJavascriptapp.post("/user/generateToken", (req, res) => {    // Validate User Here    // Then generate JWT Token      let jwtSecretKey = process.env.JWT_SECRET_KEY;    let data = {        time: Date(),        userId: 12,    }      const token = jwt.sign(data, jwtSecretKey);      res.send(token);});Create Route for Validating JWTCreating a ‘get’ request that contains the JWT token in the header and sends verification status as a response.JavascriptJavascriptapp.get("/user/validateToken", (req, res) => {    // Tokens are generally passed in the header of the request    // Due to security reasons.      let tokenHeaderKey = process.env.TOKEN_HEADER_KEY;    let jwtSecretKey = process.env.JWT_SECRET_KEY;      try {        const token = req.header(tokenHeaderKey);          const verified = jwt.verify(token, jwtSecretKey);        if(verified){            return res.send("Successfully Verified");        }else{            // Access Denied            return res.status(401).send(error);        }    } catch (error) {        // Access Denied        return res.status(401).send(error);    }});Run Servernode index.jsFull index.js FileJavascriptJavascriptconst express = require('express');const dotenv = require('dotenv');const jwt = require('jsonwebtoken');  const app = express();  // Set up Global configuration accessdotenv.config();  let PORT = process.env.PORT || 5000;app.listen(PORT, () => {  console.log(`Server is up and running on ${PORT} ...`);});  // Main Code Here  //// Generating JWTapp.post("/user/generateToken", (req, res) => {    // Validate User Here    // Then generate JWT Token      let jwtSecretKey = process.env.JWT_SECRET_KEY;    let data = {        time: Date(),        userId: 12,    }      const token = jwt.sign(data, jwtSecretKey);      res.send(token);});  // Verification of JWTapp.get("/user/validateToken", (req, res) => {    // Tokens are generally passed in header of request    // Due to security reasons.      let tokenHeaderKey = process.env.TOKEN_HEADER_KEY;    let jwtSecretKey = process.env.JWT_SECRET_KEY;      try {        const token = req.header(tokenHeaderKey);          const verified = jwt.verify(token, jwtSecretKey);        if(verified){            return res.send("Successfully Verified");        }else{            // Access Denied            return res.status(401).send(error);        }    } catch (error) {        // Access Denied        return res.status(401).send(error);    }});Send Requests and Get OutputOutput:POST RequestPOST ResponseeyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ0aW1lIjoiTW9uIEphbiAxOCAyMDIxIDE2OjM2OjU3IEdNVCswNTMwIChJbmRpYSBTdGFuZGFyZCBU
aW1lKSIsInVzZXJJZCI6MTIsImlhdCI6MTYxMDk2ODAxN30.QmWFjXhP6YtbzDAHlcE7mDMyXIdnTv1c9xOBCakNZ94GET RequestGET Request HeaderGET ResponseSuccessfully Verified
All Steps:
Create our project:To create a Node project, npm init -y is used in the folder in which the user wants to create a project. The npm command line will ask a number of questions like name, license, scripts, description, author, keywords, version, main file, etc. After npm is done creating the project, a package.json file will be visible in the project folder as proof that the project has been initialized.npm init -y
Create our project:
To create a Node project, npm init -y is used in the folder in which the user wants to create a project. The npm command line will ask a number of questions like name, license, scripts, description, author, keywords, version, main file, etc. After npm is done creating the project, a package.json file will be visible in the project folder as proof that the project has been initialized.
npm init -y
Install modulesAfter creating the project, next step is to incorporate the packages and modules to be used in the Node Project. To install packages and modules in the project use the following syntax:npm install express dotenv jsonwebtoken
Install modules
After creating the project, next step is to incorporate the packages and modules to be used in the Node Project. To install packages and modules in the project use the following syntax:
npm install express dotenv jsonwebtoken
Create our ServerImporting all the dependencies and creating a server using express.jsJavascriptJavascriptconst express = require('express');const dotenv = require('dotenv');const jwt = require('jsonwebtoken');  const app = express();  // Set up Global configuration accessdotenv.config();  let PORT = process.env.PORT || 5000;app.listen(PORT, () => {  console.log(`Server is up and running on ${PORT} ...`);});
Create our Server
Importing all the dependencies and creating a server using express.js
Javascript
const express = require('express');const dotenv = require('dotenv');const jwt = require('jsonwebtoken');  const app = express();  // Set up Global configuration accessdotenv.config();  let PORT = process.env.PORT || 5000;app.listen(PORT, () => {  console.log(`Server is up and running on ${PORT} ...`);});
Create Configuration File (.env)This files contains those variables that we need to pass to our application’s environment.JavascriptJavascriptPORT = 5000  JWT_SECRET_KEY = gfg_jwt_secret_key  TOKEN_HEADER_KEY = gfg_token_header_key
Create Configuration File (.env)
This files contains those variables that we need to pass to our application’s environment.
Javascript
PORT = 5000  JWT_SECRET_KEY = gfg_jwt_secret_key  TOKEN_HEADER_KEY = gfg_token_header_key
Create Route for Generating JWTCreating a ‘post’ request that sends the JWT token in the response.JavascriptJavascriptapp.post("/user/generateToken", (req, res) => {    // Validate User Here    // Then generate JWT Token      let jwtSecretKey = process.env.JWT_SECRET_KEY;    let data = {        time: Date(),        userId: 12,    }      const token = jwt.sign(data, jwtSecretKey);      res.send(token);});
Create Route for Generating JWT
Creating a ‘post’ request that sends the JWT token in the response.
Javascript
app.post("/user/generateToken", (req, res) => {    // Validate User Here    // Then generate JWT Token      let jwtSecretKey = process.env.JWT_SECRET_KEY;    let data = {        time: Date(),        userId: 12,    }      const token = jwt.sign(data, jwtSecretKey);      res.send(token);});
Create Route for Validating JWTCreating a ‘get’ request that contains the JWT token in the header and sends verification status as a response.JavascriptJavascriptapp.get("/user/validateToken", (req, res) => {    // Tokens are generally passed in the header of the request    // Due to security reasons.      let tokenHeaderKey = process.env.TOKEN_HEADER_KEY;    let jwtSecretKey = process.env.JWT_SECRET_KEY;      try {        const token = req.header(tokenHeaderKey);          const verified = jwt.verify(token, jwtSecretKey);        if(verified){            return res.send("Successfully Verified");        }else{            // Access Denied            return res.status(401).send(error);        }    } catch (error) {        // Access Denied        return res.status(401).send(error);    }});
Create Route for Validating JWT
Creating a ‘get’ request that contains the JWT token in the header and sends verification status as a response.
Javascript
app.get("/user/validateToken", (req, res) => {    // Tokens are generally passed in the header of the request    // Due to security reasons.      let tokenHeaderKey = process.env.TOKEN_HEADER_KEY;    let jwtSecretKey = process.env.JWT_SECRET_KEY;      try {        const token = req.header(tokenHeaderKey);          const verified = jwt.verify(token, jwtSecretKey);        if(verified){            return res.send("Successfully Verified");        }else{            // Access Denied            return res.status(401).send(error);        }    } catch (error) {        // Access Denied        return res.status(401).send(error);    }});
Run Servernode index.jsFull index.js FileJavascriptJavascriptconst express = require('express');const dotenv = require('dotenv');const jwt = require('jsonwebtoken');  const app = express();  // Set up Global configuration accessdotenv.config();  let PORT = process.env.PORT || 5000;app.listen(PORT, () => {  console.log(`Server is up and running on ${PORT} ...`);});  // Main Code Here  //// Generating JWTapp.post("/user/generateToken", (req, res) => {    // Validate User Here    // Then generate JWT Token      let jwtSecretKey = process.env.JWT_SECRET_KEY;    let data = {        time: Date(),        userId: 12,    }      const token = jwt.sign(data, jwtSecretKey);      res.send(token);});  // Verification of JWTapp.get("/user/validateToken", (req, res) => {    // Tokens are generally passed in header of request    // Due to security reasons.      let tokenHeaderKey = process.env.TOKEN_HEADER_KEY;    let jwtSecretKey = process.env.JWT_SECRET_KEY;      try {        const token = req.header(tokenHeaderKey);          const verified = jwt.verify(token, jwtSecretKey);        if(verified){            return res.send("Successfully Verified");        }else{            // Access Denied            return res.status(401).send(error);        }    } catch (error) {        // Access Denied        return res.status(401).send(error);    }});
Run Server
node index.js
Full index.js File
Javascript
const express = require('express');const dotenv = require('dotenv');const jwt = require('jsonwebtoken');  const app = express();  // Set up Global configuration accessdotenv.config();  let PORT = process.env.PORT || 5000;app.listen(PORT, () => {  console.log(`Server is up and running on ${PORT} ...`);});  // Main Code Here  //// Generating JWTapp.post("/user/generateToken", (req, res) => {    // Validate User Here    // Then generate JWT Token      let jwtSecretKey = process.env.JWT_SECRET_KEY;    let data = {        time: Date(),        userId: 12,    }      const token = jwt.sign(data, jwtSecretKey);      res.send(token);});  // Verification of JWTapp.get("/user/validateToken", (req, res) => {    // Tokens are generally passed in header of request    // Due to security reasons.      let tokenHeaderKey = process.env.TOKEN_HEADER_KEY;    let jwtSecretKey = process.env.JWT_SECRET_KEY;      try {        const token = req.header(tokenHeaderKey);          const verified = jwt.verify(token, jwtSecretKey);        if(verified){            return res.send("Successfully Verified");        }else{            // Access Denied            return res.status(401).send(error);        }    } catch (error) {        // Access Denied        return res.status(401).send(error);    }});
Send Requests and Get OutputOutput:POST RequestPOST ResponseeyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ0aW1lIjoiTW9uIEphbiAxOCAyMDIxIDE2OjM2OjU3IEdNVCswNTMwIChJbmRpYSBTdGFuZGFyZCBU
aW1lKSIsInVzZXJJZCI6MTIsImlhdCI6MTYxMDk2ODAxN30.QmWFjXhP6YtbzDAHlcE7mDMyXIdnTv1c9xOBCakNZ94GET RequestGET Request HeaderGET ResponseSuccessfully Verified
Send Requests and Get Output
Output:
POST Request
POST Response
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ0aW1lIjoiTW9uIEphbiAxOCAyMDIxIDE2OjM2OjU3IEdNVCswNTMwIChJbmRpYSBTdGFuZGFyZCBU
aW1lKSIsInVzZXJJZCI6MTIsImlhdCI6MTYxMDk2ODAxN30.QmWFjXhP6YtbzDAHlcE7mDMyXIdnTv1c9xOBCakNZ94
GET Request
GET Request Header
GET Response
Successfully Verified
NodeJS-Questions
Technical Scripter 2020
Node.js
Technical Scripter
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.