How to implement JWT Authentication in Node-js API

In this post, I will be introducing to you JWT (JSON Web Tokens) Technology which lets you do http requests with protected access i.e. some kind of token is returned in the JSON response. And with the help of this token you will be making the request. After getting the token you can save the token to Cookies (Not Recommended anymore) but you can save these tokens to LocalStorage. The upcoming requests you make to the server will contain the header with this web token. In this tutorial we will be making a simple Node.js API and then we will be applying some kind of Authentication with the help of JWT. Let’s get started with the post.

Examples of JWT

Some of the noteworthy examples where you can find these JWT being used are the OAuth login systems of various social media sites such as google, facebook , github, twitter etc. When you make a OAuth request you need to get a access token to request user data from the social media provider. Similarly they uses JWT under the hood to implement this functionalty. Now in this blog post we will making our own system i.e. own api, making requests to the api to access the data. And in the process we will be implementing Authentication to that data so that only users have the JWT can access the API.

Prerequisites

  1. Basic Knowledge of Node is required.
  2. Basic Knowledge of Postman is required.

Requirements

  1. Postman : It will be the tool from which we will making our requests. You can download the tool from here
  2. Visual Studio Code : It will be the Text Editor on which we will be writing our code.
  3. Node : You should have node installed on to your computer.

Postman

Postman is GUI Tool for both mac,windows and linux to make HTTP requests to the server. It makes the job more easier by providing the right tools to make HTTP requests. As you know curl and more command prompt tools are so cumbersome to use. You can see the look of postman given below. How beautiful is the interface of the tool.

Here you can see in the above figure we can send requests by specifying the URL property in the input textfield. Apart from that we have also the option to add additional HTTP headers on that request.

Creating Project

First of all create a new directory where you will create your node project. Enter the directory after creating it and open command line inside the directory and issue this command which is shown below.

After executing this command npm init it will ask you some questions about the project that what name you want to give your project, description of project, author name, license and all that stuff. Just go through that and lastly it will create the package.json file from the data you provided earlier. So the package json file will look like something like this.

This contains all the information about your project. Now the next thing we need to do is install some dependencies which will be required to make this project.

Installing Dependencies

  1. Nodemon: First of all we will install Nodemon it is required because we don’t want to restart server again and again when any kind of change is made to the application. It will automatically do that task for us. This will be a dev depedency (Development Dependency).

After installing it successfully. Now just start the nodemon server something like this

Actually index.js will be our main startpoint script file. Here we are just starting it. Obviously we will write code

in it later.

  1. Installing Express & JWT :  Now we will install the two main dependencies of the project. Just write this command as shown below.

After installing these dependencies the package.json file will look something like this

Now create a new index.js file and in that file we will write our code. And in that file first of all we will be importing the dependencies that we have installed earlier i.e. express and jwt. And then after that we will be starting our server at Port 5000 you can take any port number of your choice. In that port number the server will be receiving requests from the user. When the user requests the url at that port we will sending a json response back to the browser. In postman later we will see the response coming back from the api.

const express = require('express');

const jwt = require('jsonwebtoken');

const app = express();

app.get('/api',(req,res) =>{
    res.json({
        message:'Welcome to the API'
    })
})

app.listen(5000,() => console.log('Server started on Port 5000'))

Now if we run this by writing nodemon index.js command in command prompt we will see the following output.

So our server started at Port 5000 as shown above. Now if we open the Postman Software and make a get request at the following url http://localhost:5000/api we shall get a json response back from the api something like this.

So you can see above we get a json response back from the api i.e. welcome to the api the same text that we have written in the code. So we can now make a basic send request to the api.

Similarly we can now make a post request to the api also. We will now write a post request in our code. We will not use in any kind of form but a simple post request for which we will returning some message.

app.post('/api/posts',(req,res) =>{
    res.json({
        message:'Post successfully created'
    })
})

So again when we open postman this time we will be selecting post in the method type and type this url http://localhost:5000/api/posts we shall receive a response something like this

So we get a similar json response post successfully created. Now we need to add some authentication to our api. So that not everyone can access our api. The authentication part will be handled by jwt library.

So first of all we will again create a post request but now we will have authentication attached to that request. In this first of all we will create a mock user through which we will be implementing authentication. You can also save users in a database and do authentication but for this simple tutorial we will create a random user and use that in it. So create a mock user something like this.

app.post('/api/login',(req,res) =>{
   const user ={
       id : 1,
       username: 'Gautam',
       email: 'gautam@gmail.com'
   }

So this user has three fields you can see the id, username and email address. So after creating this we will calling the jwt sign method which takes the payload data in this case the user object, secondly it takes the secret key which you have to pass you can name anything you want but i have named secretkey just for easy understanding and lastly we have the callback function which will run if the authentication is successful. We have two variables err and token if authentication is not successful then error will be thrown which is stored inside err variable but if authentication is successful then the token will be returned in the json response whenever user hits the url.

jwt.sign({user:user},'secretkey',(err,token) =>{
       res.json({
           token:token
       })
   })

So after that if we run the application and open postman and send a post request to the url http://localhost:5000/api/login we shall get this result as shown below.

So you can see that a token is returned in the json response when we send the post request to the url. This token contains all the information that we will need to make a protected request to a route which we don’t have write now. Now we will create that route.

Now we will be moving back to the posts route that we have created earlier in the post. We will protect that route so that only authenticated users can access that route. For adding authentication we will be first of all adding the middleware function to that route something like this.

app.post('/api/posts',verifyToken,(req,res) =>{
    res.json({
        message:'Post successfully created'
    })
})

In this code we are calling the custom middleware function i.e. verifyToken. We will create this function now in this function we will be verifying the token which is generated earlier. This function takes req , res, and next which will continue from middleware to the actual post request.

function verifyToken(req,res,next)
{
}

The first thing we will do in this function is that we will be grabing the authorization header from the request. The Authorization header is actually Bearer {Actual Token}. Here Bearer is a term used in Authorization header. So we will be grabing the whole header and checking if it is undefined or not.

if(typeof bearerHeader !== 'undefined')
    {

    }else{
        res.sendStatus(403);
    }

If the Authorization header is undefined then we can simply send the response status to 403 i.e. forbidden. It actually means that we are saying to the user that the resource requested by the user doesn’t exist. Because you are not eligible to make the request i.e. you don’t have the token.

After this if the token is there with the user then we will split the token from the Bearer text something like this

const bearer = bearerHeader.split(' ');
      const bearerToken = bearer[1];
      req.token = bearerToken;
      next();

In this section of code we are first of all splitting the token and the bearer text with the help of split function. Split function actually splits the string into an array. In this case we are splitting the string by a space and then we have the array containing the bearer and the token in two indices. First indice holds the Bearer text and the second indice will hold the token. So we can access the token by bearer[1] as array starts from 0. Then after extracting the token we are setting the token to the request token and then we are calling the next function to continue from the middleware to the post request.

[

Now if we make a post request to http://localhost:5000/api/posts then it should return forbidden as shown below because now it is a protected resource

Now we will go back to the posts route and write some checks in order to verify that the token which is entered by the user is correct or not. So for that we will be using the JWT verify function which takes the actual token which is passed by req.token and the second argument will be the secretkey again and you can give any name of your choice and lastly we will be having two variables err and authdata which represents the error and the actual authdata which will be send in the json response which includes the id, username and email address if the authentication is successful. So if any kind of error takes place we will be sending the forbidden status code of 403. And if all goes right we will be sending the post message as well as the authdata.

app.post('/api/posts',verifyToken,(req,res) =>{

    jwt.verify(req.token,'secretkey',(err,authData) =>{
        if(err){
            res.sendStatus(403)
        }
        else{

            res.json({
                message:'Post successfully created',
                authData:authData
            })

        }
    })
})

Now if we make a postman post request to the login route then a token will be generated something like this

Now if we copy paste this token and send it as a Authorization header to the api/posts route then we shall get the authdata and post message

Now you can see that the json response includes the post message and the authdata which includes the user object which contains the id, username and email address of the user which we have created earlier. And also a issued at token is also generated which is actually a timestamp.

Now we can also add a expiration time to the token which is generated so that it can’t be there for all the time. It is very necessary for the applications to have the expiry time for the token. For this we will going back to the login route and edit the jwt sign method in that just add this expiresIn field and after that give how many seconds you want for token to expire. I am giving 30 seconds you can give any value of your choice.

jwt.sign({user:user},'secretkey',{expiresIn:'30s'},(err,token) =>{
       res.json({
           token:token
       })
   })

Now the Application is complete. Ofcourse we are using Postman but you can extend this application by using a front end such as Angular or Vuejs to make the http request. The full source code of the application is given below.

const express = require('express');

const jwt = require('jsonwebtoken');

const app = express();

app.get('/api',(req,res) =>{
    res.json({
        message:'Welcome to the API'
    })
})

app.post('/api/posts',verifyToken,(req,res) =>{

    jwt.verify(req.token,'secretkey',(err,authData) =>{
        if(err){
            res.sendStatus(403)
        }
        else{

            res.json({
                message:'Post successfully created',
                authData:authData
            })

        }
    })
})

app.post('/api/login',(req,res) =>{
   const user ={
       id : 1,
       username: 'Gautam',
       email: 'gautam@gmail.com'
   }

   jwt.sign({user:user},'secretkey',{expiresIn:'30s'},(err,token) =>{
       res.json({
           token:token
       })
   })
})

function verifyToken(req,res,next)
{
    const bearerHeader = req.headers['authorization'];
    if(typeof bearerHeader !== 'undefined')
    {
      const bearer = bearerHeader.split(' ');
      const bearerToken = bearer[1];
      req.token = bearerToken;
      next();

    }else{
        res.sendStatus(403);
    }
}

app.listen(5000,() => console.log('Server started on Port 5000'))

Thank you for reading, Please share if you liked it!

#node-js #jwt #api #postman #vscode

How to implement JWT Authentication in Node-js API
24.20 GEEK