Login App – Create REST API for authentication in Node.js using JWT – Part 2

In this article, we will show you how to create REST API for authentication in Node.js using JWT. As we already discussed the implementation flow of login/authentication functionality in First part of the article so now it’s time to move on to the second part of the article to create secure REST API in Node.js.

Before you continue, we want you to check out the first part of this article.

Way to create REST API for authentication in Node.js

  1. Create simple REST API in Node.js
  2. Install all the required npm packages
  3. Define the environment variable
  4. Manage general utility
  5. Create API for user sign in
  6. Create API for verify token
  7. Implement middleware to validate the token
  8. Output

1. Create simple REST API in Node.js

To begin the implementation, We have to start with simple REST API integration in Node.js. If you don’t know about it then refer the following link to create REST API.

Create REST API in Node.js

We will set up a file structure like the one below.

File Structure - Create REST API for authentication in Node.js using JWT - Clue Mediator
File Structure – Create REST API for authentication in Node.js using JWT – Clue Mediator

2. Install all the required npm packages

Run the following command to install the required dependencies.

After a successful installation, you will need to enable the middleware and use it in the server file to handle the request. Check out the following code of the server.js where we use it.

3. Define the environment variable

We must have a JWT secret key to manage the token so we need to create a .env file in the project directory. It should look like below.

.env

Now we can use “JWT_SECRET” variable via calling process.env.JWT_SECRET from any files. But we have to add require('dotenv').config(); at the top of the server.js file.

4. Manage general utility

utils.js

5. Create API for user sign in

Here, we can consider the static data to validate the user therefore we will declare user information in the variable of the server file.

Let’s start creating the API where the user can get authenticated bypassing the login credentials. If the user gets authenticated successfully then we will create a token and return it back.

6. Create API for verify token

Now let’s create another API where we can verify the token and based on the given response we can manage the routes in React Application. If token is invalid then we will send “401 Unauthorized” response to the user.

7. Implement middleware to validate the token

At last we need to implement the middleware so we can verify the token for private routes. If token is not exist in the header of the request then we can directly pass the request to the next route and if it’s exist then we will verify it and append the user object to the same request and pass it to the next route so in the next route we can use the user object.

Basically this helps to know if the request is authenticated or not.

8. Output

At the end of the development, your server.js file should look like below.

server.js

That’s it for today. Now you can check these APIs in postman or any other tools.

Output - Create REST API for authentication in Node.js using JWT - Clue Mediator
Output – Create REST API for authentication in Node.js using JWT – Clue Mediator

In Part 3 of this article, we’ll create login form in ReactJS using secure REST API

In this article, we have covered the general straight forward flow of the authentication. Check out the below article where you will find the more secure way to implement authentication including refresh token and CSRF protection.

Login App with CSRF protection

Thanks for reading. Happy Coding!

Demo & Source Code

Github Repository Postman Collection

You may also like...

25 Responses

  1. Vova says:

    Hi Clue,
    Thanks for the article!!!
    I wonder how to create not “static user details” … for instance json file or something like that. I want create more admins

    • Clue Mediator says:

      Hello Vova,
      I’m glad you like the article.

      Below code will help you to read/write json file instead of static users.


      var fs = require('fs');
      ...
      ...
      var users = [];
      ...
      fs.readFile('jsonfile.json', 'utf8', function readFile(err, data){
      if (err){
      console.log(err);
      return false;
      }
      const obj = JSON.parse(data); // parse data from string
      obj.push({id: 2, square:3}); // add some data
      const json = JSON.stringify(obj); // convert it back to JSON format
      fs.writeFile('jsonfile.json', json, 'utf8', callback); // write it back
      }});
      ...
      ...

      Like & Share with your friends. Happy Coding..!!

      • Vova says:

        Thanks Clue!
        This part of code should have separate file? or I can add it to server.js file?

        • Vova says:

          I made something like this:
          const users = [
          {
          userId: “789789”,
          password: “123456”,
          name: “Mike X”,
          username: “mike”,
          isAdmin: true
          },
          {
          userId: “7333333”,
          password: “123456”,
          name: “Joe”,
          username: “joe”,
          isAdmin: true
          },
          ]

          let userData = users.find(obj =>{
          return obj.username === “joe”
          })

          How can I check “username” as variable instead of write “joe” ?

        • Clue Mediator says:

          Hello Vova,
          I would recommend you to take separate file instead of variable in server.js file. You can also use database instead of it.

          – Thanks

  2. Edwin says:

    Hi clue, I’m getting a ‘token not defined’ on utils.js file

    • Clue Mediator says:

      Hi Edwin,
      Sorry, We made a mistake in “generateToken” function. Can you please check it and let me know if you are still facing an issue.

      Thank you for pointing our attention there.

      Follow us on Facebook & Twitter to get latest update.
      – Clue Mediator

  3. Abhijit says:

    i’m not able to perform multi-user auth for above example …can you guys help with sample code or stuff?

    • Clue Mediator says:

      Hi Abhijit,
      What do you mean by multi-user auth? Can you please explain more?

      We’ll try our best to help you.

  4. Abhijit says:

    yeah like above example is for static single user sign-in ,
    i’m trying to implement sign-ins for more than one user…like have 4 users, 2 are admins and like that
    i’m noobie in node backend, thanks for help

    • Clue Mediator says:

      Hi Abhijit,
      You have to implement the role based application to manage the multi role user login.

      Let me add this topic in my list. We will write separate article on it.

      You can subscribe us for weekly email update of our news & articles.

      Like us on Facebook & Share it. Happy Coding..!!!

      – Clue Mediator

  5. Abhijit says:

    Ok….looking forward to it

  6. Tobias says:

    Hello,

    very nice article to read and to understand how that all works. I have one question: If I have other backend routes too, that should be protected by the token how do I verify that the user is loggedin ?

    • Clue Mediator says:

      Hello Tobias,
      We glad you like it.

      Let’s talk about your queries. Are you talking about the other backend technologies or other private routes?

      If you are talking about the private routes then you should have separate middleware where you can verify the token for each request and based on that you can manage the logged-in status.

      In this article, we have covered the general straight forward flow of the authentication. Check out the below article where you will find the more secure way to implement authentication including refresh token and CSRF protection.

      Login App with CSRF protection – Understanding authentication using JWT access token and refresh token

      We are still working on it to serve two more articles related to it.

      Hope you like it.

      Subscribe us for weekly updates or like and follow us for regular updates.

      – Clue Mediator

  7. Tobias Dethleffsen says:

    thanks Clue. The linked article sounds like what I am searching for. I am looking forward to read it if it is finished.

    • Clue Mediator says:

      Great, You will get a bunch of articles by next week.

      Keep in touch and share it with your friends.

      Happy Coding..!!

  8. gurudeep shrotriya says:

    Hey Clue! While posting signin request over Postman, I’m getting following error:
    {
    “error”: true,
    “message”: “Username or Password required.”
    }
    I checked with your code..everything is same still I’m getting this error

    • Clue Mediator says:

      Hello Gurudeep,

      Are you passing the username and password via users/signin post request? You can also clone the Github repository and use the postman collection that we have provided at the bottom of the post because I have tested it and it’s working with the existing demo.

      Let me know if you are still facing any issues.

      Subscribe us for weekly updates or like and follow us for regular updates.

      Happy Coding..!!

  9. Mor Mauda says:

    Hi,

    Thanks for this!

    Do you familiar with the problem of :

    You need to enable JavaScript to run this app.

    when trying to run GET request from postman for “http://localhost:3000” ?

    • Clue Mediator says:

      I would guess your GET request URL is wrong. Please try to access it from the browser so you can get more idea about the error.

  10. kamal says:

    Hi,

    Thanks for this!

    Can you please give register form example with same flow

  11. saif says:

    can you please let me know where to add the below code to add multiple users instead of static users?

    var fs = require(‘fs’);


    var users = [];

    fs.readFile(‘jsonfile.json’, ‘utf8’, function readFile(err, data){
    if (err){
    console.log(err);
    return false;
    }
    const obj = JSON.parse(data); // parse data from string
    obj.push({id: 2, square:3}); // add some data
    const json = JSON.stringify(obj); // convert it back to JSON format
    fs.writeFile(‘jsonfile.json’, json, ‘utf8’, callback); // write it back
    }});

    • Clue Mediator says:

      Hello Saif,
      In the current article, we are only reading the data to verify them. So I suggest you create a new promise based function and write code to get the list of the user from the JSON file. Call this newly created method from signin API.

      Let us know if you still have any doubts.

Leave a Reply

Your email address will not be published. Required fields are marked *