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
How to avoid getting stung by bees, wasps and hornets - Farm and Dairy
Is everyone replaceable at Netflix? | LinkedIn
EY – все про компанію - Happy Monday
How To Get Free Credits On Smartjailmail
270 West Michigan residents receive expert driver’s license restoration advice at last major Road to Restoration Clinic of the year
Cvs Devoted Catalog
3656 Curlew St
Used Wood Cook Stoves For Sale Craigslist
Aces Fmc Charting
A Guide to Common New England Home Styles
Darksteel Plate Deepwoken
Colorado mayor, police respond to Trump's claims that Venezuelan gang is 'taking over'
SXSW Film & TV Alumni Releases – July & August 2024
Sport-News heute – Schweiz & International | aktuell im Ticker
Foxy Brown 2025
How To Level Up Roc Rlcraft
Craigslist Appomattox Va
Caledonia - a simple love song to Scotland
What Is Vioc On Credit Card Statement
[Cheryll Glotfelty, Harold Fromm] The Ecocriticism(z-lib.org)
We Discovered the Best Snow Cone Makers for Carnival-Worthy Desserts
Big Lots Weekly Advertisem*nt
Putin advierte que si se permite a Ucrania usar misiles de largo alcance, los países de la OTAN estarán en guerra con Rusia - BBC News Mundo
Japanese Mushrooms: 10 Popular Varieties and Simple Recipes - Japan Travel Guide MATCHA
Magic Seaweed Daytona
Understanding Gestalt Principles: Definition and Examples
Danielle Ranslow Obituary
Koninklijk Theater Tuschinski
6892697335
Hesburgh Library Catalog
No Limit Telegram Channel
Claio Rotisserie Menu
Florence Y'alls Standings
Hoofdletters voor God in de NBV21 - Bijbelblog
60 Second Burger Run Unblocked
Gina's Pizza Port Charlotte Fl
Southern Democrat vs. MAGA Republican: Why NC governor race is a defining contest for 2024
Jewish Federation Of Greater Rochester
The Closest Walmart From My Location
SF bay area cars & trucks "chevrolet 50" - craigslist
Homeloanserv Account Login
Florida Lottery Claim Appointment
Busted Newspaper Mcpherson Kansas
Chubbs Canton Il
Lesson 5 Homework 4.5 Answer Key
Congruent Triangles Coloring Activity Dinosaur Answer Key
Craigslist Pets Charleston Wv
Round Yellow Adderall
Aspen.sprout Forum
Cataz.net Android Movies Apk
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.