Node.js

How to Create a Node.js Authentication API Using JWT Tokens

We’ll learn how to utilize JWT in Node.js to secure endpoints and even authenticate users in this blog.

Writing code and developing applications is quite simple. However, how do we handle authentication and, more importantly, authorization?

Prerequisites

You’ll need the following items to follow along with this tutorial:

  • A basic understanding of JavaScript is required.
  • A decent comprehension of Node.js.

Let’s get started,

Setup nodejs project and add a basic setup in your project. I can start to implement register and login functionality.

In our application, we’ll build these two routes. Before putting the credentials in your database, we’ll use JWT to sign them and bycrypt to encrypt them (at the moment, I’ll use console.log()).

We’ll do the following with the /register route:

  • Get user details
  • Validate the input of the user.
  • Encrypt the password for the user.
  • Finally, produce a JWT token that has been signed.

Before the start implement on the project. we need to add npm packages to our node js project.

npm install jsonwebtoken 
npm install bcryptjs

Add dependencies in the app.js file

const jwt = require('jsonwebtoken');
const bcrypt = require('bcrypt');

app.js

..//

app.post("/register", async (req, res) => {
  try {
    // get user input
    const { first_name, last_name, email, password } = req.body;

    // Validate user input
    if (!(email && password && first_name && last_name)) {
      res.status(400).send("All input is required");
    }

    // check if user already exist
    // Validate if user exist in our database
    //const oldUser = callyourDbfunction();

    //if (oldUser) {
    // return res.status(409).send("User Already Exist.");
    //}

    //Encrypt user password
    encryptedPassword = await bcrypt.hash(password, 10);
    console.log("Encrypted Password", encryptedPassword);

    // save the user in the database.

    // Create token
    const token = jwt.sign(
      { user_id: user._id, email },
      'YOURSECRETKEY',
      {
        expiresIn: "2h",
      }
    );
    // save user token
    user.token = token;

    // return new user
    res.status(201).json(user);
  } catch (err) {
    console.log(err);
  }
});

Using Postman to test the endpoint.

We’ll do the following with the /login route:

  • Get user details
  • Validate the input of the user and check if the user exists.
  • Check the user password against the password we saved in the database.
  • Finally, produce a JWT token that has been signed.
..//

app.post("/login", async (req, res) => {

  try {
    // Get user data
    const { email, password } = req.body;

    // Validate user input
    if (!(email && password)) {
      res.status(400).send("All input is required");
    }
    // Validate if user exist in our database
    const user = finduserbymail(email);

    if (user && (await bcrypt.compare(password, user.password))) {
      // Create token using jwt
      const token = jwt.sign(
        { user_id: user._id, email },
        'YOURSECRETKEY',
        {
          expiresIn: "2h",
        }
      );

      // save the token in user response
      user.token = token;
      res.status(200).json(user);
    }
    res.status(400).send("Invalid Credentials");
  } catch (err) {
    console.log(err);
  }
});

Using Postman to test the endpoint.

Create authentication middleware.

We’ve created and logged in a user successfully. Regardless, we’ll create a route that requires a user token in the header, which will be the JWT token we generated before.

Inside auth.js, add the following line.

const jwt = require("jsonwebtoken");
const verifyToken = (req, res, next) => {
  const token =
    req.body.token || req.query.token || req.headers["x-access-token"];

  if (!token) {
    return res.status(403).send("A token is required for authentication");
  }
  try {
    const decoded = jwt.verify(token, 'YOURSECRETKEY');
    req.user = decoded;
  } catch (err) {
    return res.status(401).send("Invalid Token");
  }
  return next();
};

module.exports = verifyToken;

To test the middleware, create the /welcome route and edit app.js with the following code.

app.js

const auth = require("./auth");

app.post("/welcome", auth, (req, res) => {
  res.status(200).send("Hello world");
});

That’s it. you can add the token in the header with the key x-access-token.

I hope you guys understand how I can do this. Let me know if you face any difficulties.

You can watch my previous blog here.

Happy Coding {;}

Nayan Raval

Nayan Raval is a MEAN Stack .Net Developer has extensive experience with designing and developing enterprise-scale applications. Key Areas Of Expertise: • ASP.NET Core MVC • ASP.NET Core Web API • C# • ASP.NET MVC 5 • Angular All versions • HTML5 • CSS3 / SCSS • Bootstrap • JavaScript • Azure • JQuery Databases and related • Microsoft SQL server MSSQL • PostgreSQL • Entity Framework (EF) • LINQ UI Frameworks • Kendo UI • Telerik • JQuery UI • Prime NG and Material UI API Integration • SignalR • DateDog • Twilio Voice Call And Message • Stripe • SendGrid (Email Camping) • Checkr • Zoom Video Call • Auth0 • Elastic Search • Quartz - Scheduler • JWT Token • Google Calendar

Recent Posts

Testing hk

Testing

2 years ago

Create and Used PIPE in angular

In this article, we have to show Create and Used PIPE in angular

2 years ago

Operation

Testing

2 years ago

Create and Used PIPE in angular

In this article, we have to show Create and Used PIPE in angular

2 years ago

Create and Used PIPE in angular

In this article, we have to show Create and Used PIPE in angular

2 years ago

TETS NEW

test

2 years ago