How to Create and Verify JWTs with Node? - GeeksforGeeks (2024)

Last Updated : 25 Jul, 2024

Summarize

Comments

Improve

In this article, we will see how to create JWT tokens in Node.js. We will implement secure authentication in Node.js by creating and verifying JSON Web Tokens (JWTs) using libraries like `jsonwebtoken`.

Prerequisites:

  • Good knowledge of JavaScript.
  • Basic knowledge about Express JS.
  • Basic knowledge about API Authentication.
  • Basic knowledge about postman and their uses.

Steps to Implement and Verify JWT

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

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:

How to Create and Verify JWTs with Node? - GeeksforGeeks (1)

The updated dependencies in package.json file will look like

"dependencies": {
"express": "^4.18.2",
"jsonwebtoken": "^9.0.2",
"nodemon": "^3.0.2",
}

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.

Approach

  • Before create and verify the API endpoint with the help of JWT, and express firstly write some code for further use.
  • After the dummy code is ready, then create a json database object and store some dummy data.
  • Allow JSON data to make communicate with API. Allow the JSON data in a request by adding middleware for the body parser.
  • 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.
  • 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.
jwt.sign(
{data_obeject},
"secret_key",
{Options}
)
  • Now we will make another route for authentication jwt token. Here, we create an authentication route and authenticate the coming JWT token.
// 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 with error
res.json({
login: false,
data: 'error'
});
}
});

  • 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.
jwt.verify(token_value, 'secret_key');

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

Node
// index.js// 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 database = [ { 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 isPresentIndex = null; // iterate a loop to the data items and // check what data are matched. for (let i = 0; i < database.length; i++) { // If data name are matched so check // the password are correct or not if (database[i].name === name && database[i].password === password) { // If both are correct so make  // isPresent variable true isPresent = true; // And store the data index isPresentIndex = 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(database[isPresentIndex], "secret"); // Pass the data or token in response res.json({ login: true, token: token, data: database[isPresentIndex], }); } 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.

Output: Send a POST request to localhost at ‘/login’ with login data, receive a JSON response with login status and token/object data, then use the token to authenticate a GET request to ‘/auth’. After validation, you will get the proper data object store in the token.



mrsuryapratap

How to Create and Verify JWTs with Node? - GeeksforGeeks (3)

Improve

Next Article

How to create Telegram Chatbot with Node.js ?

Please Login to comment...

How to Create and Verify JWTs with Node? - GeeksforGeeks (2024)
Top Articles
Microsoft is testing a built-in crypto wallet in Microsoft Edge
Will Coinbase Refund Your Crypto if You're Scammed?
Libiyi Sawsharpener
Occupational therapist
Chambersburg star athlete JJ Kelly makes his college decision, and he’s going DI
Ingles Weekly Ad Lilburn Ga
<i>1883</i>'s Isabel May Opens Up About the <i>Yellowstone</i> Prequel
Canelo Vs Ryder Directv
Mikayla Campinos Videos: A Deep Dive Into The Rising Star
Horned Stone Skull Cozy Grove
Umn Biology
Matthew Rotuno Johnson
Large storage units
What’s the Difference Between Cash Flow and Profit?
Builders Best Do It Center
Enderal:Ausrüstung – Sureai
The Witcher 3 Wild Hunt: Map of important locations M19
Dr. med. Uta Krieg-Oehme - Lesen Sie Erfahrungsberichte und vereinbaren Sie einen Termin
Letter F Logos - 178+ Best Letter F Logo Ideas. Free Letter F Logo Maker. | 99designs
Www.publicsurplus.com Motor Pool
Roane County Arrests Today
Construction Management Jumpstart 3Rd Edition Pdf Free Download
Aliciabibs
Hellraiser 3 Parents Guide
Firefly Festival Logan Iowa
Xxn Abbreviation List 2023
Tamil Movies - Ogomovies
Stephanie Bowe Downey Ca
Generator Supercenter Heartland
Log in to your MyChart account
Himekishi Ga Classmate Raw
Blush Bootcamp Olathe
Prévisions météo Paris à 15 jours - 1er site météo pour l'île-de-France
Sf Bay Area Craigslist Com
Lil Durk's Brother DThang Killed in Harvey, Illinois, ME Confirms
Adecco Check Stubs
New Gold Lee
Quake Awakening Fragments
What Does Code 898 Mean On Irs Transcript
20 bank M&A deals with the largest target asset volume in 2023
SF bay area cars & trucks "chevrolet 50" - craigslist
Lucifer Morningstar Wiki
LumiSpa iO Activating Cleanser kaufen | 19% Rabatt | NuSkin
Florida Lottery Powerball Double Play
CrossFit 101
Canonnier Beachcomber Golf Resort & Spa (Pointe aux Canonniers): Alle Infos zum Hotel
Costner-Maloy Funeral Home Obituaries
Dietary Extras Given Crossword Clue
Uncle Pete's Wheeling Wv Menu
라이키 유출
Ok-Selection9999
Texas Lottery Daily 4 Winning Numbers
Latest Posts
Article information

Author: Aron Pacocha

Last Updated:

Views: 5914

Rating: 4.8 / 5 (68 voted)

Reviews: 91% of readers found this page helpful

Author information

Name: Aron Pacocha

Birthday: 1999-08-12

Address: 3808 Moen Corner, Gorczanyport, FL 67364-2074

Phone: +393457723392

Job: Retail Consultant

Hobby: Jewelry making, Cooking, Gaming, Reading, Juggling, Cabaret, Origami

Introduction: My name is Aron Pacocha, I am a happy, tasty, innocent, proud, talented, courageous, magnificent person who loves writing and wants to share my knowledge and understanding with you.