Open In App

How to Create and Verify JWTs with Node?

Improve
Improve
Like Article
Like
Save
Share
Report

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

Prerequisites:

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

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:

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

Javascript




// Import express for creating API's endpoints
const express = require("express");
 
// Import jwt for API's endpoints 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 fake database object
let database = [
    {
        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 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 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",
        });
    }
});
 
// 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.

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.



Last Updated : 14 Jan, 2024
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads