🔐 Node.js API Authentication With JSON Web Tokens

Introduction

 
In this article, we are going to cover how to access the JSON web token (jwt) and also to protect our routes by the JSON web token.
 
Have you ever thought about the process of authentication? What lies under the layers of abstraction and complexity? Nothing out of the ordinary. It's a method of encrypting data and generating a one-of-a-kind token that users can use to identify themselves. Your identity is verified with this token. It will verify your identity and grant you access to a variety of services. If you don't recognize any of these words, don't worry, I'll explain everything below.
 

Setup

 
Before we get started into this we should have few things installed in our machine.
Prerequisites & Dependencies
 
Create a new folder with project name (NodeAuthAPI) and open the same folder in Visual Studio Code (VS Code)
 
Run the following command to initialize our package.json file.
  1. npm init --yes  
 Install all our remaining dependencies
  1. npm install express jsonwebtoken  
  1. npm install -g nodemon   

Why these Dependencies?

 
express - running on the server (Port number)
 
jsonwebtoken - This will be used to sign and verify Json web tokens.
 
nodemon - will use this to restart our server automatically whenever we make changes to our files.
 
Create a file named index.js inside the project.
 
Project Structure
 
 
 
Let's import the packages in index.js file 
  1. const express = require("express");  
  2. const jwt = require("jsonwebtoken");  
 Now initialize the app variable with express
  1. const app = express();  
setup the port number for our server to process
  1. app.listen(5000,()=>console.log('listening on port 5000'));  
 Let's run and test whether our app is running under the same port number which we mentioned above.
 
Run the command in the terminal - nodemon  to check the output 
 
 
 
Create a simple get method to check the output in Postman.
 
index.js
  1. app.get('/api',(req, res) => {  
  2.     res.json({   
  3.         message: 'Welcome to the API!',  
  4.     });  
  5. });  
Postman
 
 
So it is confirmed that our get method is working as expected, Now configure the jwt setup to check with the actual authentication mechanism. Create a post API Login Method with Mock username and Email and also i have setup the token expiration seconds in the same method.
  1. app.post('/api/Login',(req, res) => {  
  2.     //Mock user  
  3.     const user ={  
  4.         username: 'jk',  
  5.         email: '[email protected]'  
  6.     }  
  7.     jwt.sign({user:user},'secretkey',{expiresIn: '30s'},(err,token)=>{  
  8.         res.json({token})  
  9.     })  
  10. })  
Postman
 
 
The token is generated with basic credentials, Now we need to validate another API with this token to access the credentials.
 
Create a function and verify the token which will be passed as a header 
 
 Sample   Authorization :   Bearer <your token>
  1. //Access token  
  2. //Authorization : Bearer <access token> 
  3.   
  4. //Verify Token  
  5. function verifyToken(req, res,next) {  
  6.     //Get Auth header value  
  7.     const bearerHearder = req.headers['authorization'];  
  8.     //check if bearer is undefined  
  9.     if(typeof bearerHearder != 'undefined'){  
  10.         //split at the space  
  11.         const bearer = bearerHearder.split(' ');  
  12.         //Get the token from array  
  13.         const bearerToken = bearer[1];  
  14.         // set the token  
  15.         req.token = bearerToken;  
  16.         //Next middleware  
  17.         next();  
  18.   
  19.     }else{  
  20.         //Forbidden  
  21.         res.sendStatus(403);  
  22.     }  
  23. }  
Let's create an API to validate this token 
  1. // Post to Validate the API with jwt token  
  2. app.post('/api/validate',verifyToken,(req, res)=>{  
  3.     jwt.verify(req.token,'secretkey',(err,authData)=>{  
  4.         if(err){  
  5.             res.sendStatus(403);  
  6.         }else{  
  7.             res.json({  
  8.                 message: 'Validated',  
  9.                 authData  
  10.             });  
  11.         }  
  12.     });  
  13. });  
Testing with Postman
 
 
If you are trying to access the validate API without passing the token it will give us 403 Forbidden because of unauthorized access.
 
Now let's get the token first by accessing the Login API and then pass the same token as the header in the Validate API to get the access and as well as result.
 
 
 
Note 
After 30 sec the token will expire because we defined the expiration time in code, we need to get the token again by accessing the login API  
Thanks for reading this article, Hope you got a clear picture in understanding this Node.js API Authentication with jwt.
 
...Keep learning !!!


Similar Articles