API Authentication with JWT Token in Node.js
JSON Web Token(JWT) defines a way to transmit information securely between parties. Digital signature is a way to encrypt the information. This signature contains a public/private key.
Here we will discuss why JSON web tokens are useful -
Authorization: This is very common scenario for using JWT. Once user logged in and if the user is verified then all the request by that user later on, during the session period, will be protected by that JWT.
Secure Routing: An authorized user now can access the information till the signed token is valid.
JSON Web Token structure
JSON Web Tokens consist of three parts separated by dots (.
), which are:
- Header
- Payload
- Signature
Now, let see the implementation of JWT to authorize a user and routing APIs securely. In this article, we will use Node and Express.
So, at very first we need to install some dependencies -
npm i express;
npm i jsonwebtoken;
Now we will see when it gets input from user how the user gets validated. For example, In a simple post method it accepts name and mail id from user and search it in database. If it is found then a signed web token will be generated.
Let’s create a file named index.js.
const express = require("express");
const jwt = require('jsonwebtoken');app.use(express.json());app.listen(2400, 'server listening at port 2400');const EmployeeData = [{
eid: '1' ,
name: 'Sam',
mail: 'abc@mail.com'
},{
eid: '2' ,
name: 'Mira',
mail: 'jkl@mail.com'
},{
eid: '3' ,
name: 'Dev',
mail: 'xyz@mail.com'
}]app.post('/login',function(req,res,next){
let input = {name: req.body.name, mail: req.body.mail};
let user = EmployeeData.find(d=>d.name===input.name && d.mail===input.mail);if(user){
const token=jwt.sign({user:user}, 'secret', {expiresIn: '24h'})
//'secret' is key here. you can use any random key as private.
//expiresIn helps to expire the session of user. you can set the time according to your need. either you can set time as string '2h','30m' else can set as seconds {expiresIn: 60} user.token = token;res.status(200).json(user);}else {res.send('Not Found');}
});
Now run the command -
node index.js
The server will listen at port 2000. Next, go to postman and test the api -http://localhost:2000/login. In body pass this object-
{
"name" : "Sam",
"mail" : "abc@mail.com"
}
In postman, you will get the response as shown below:
In response we see a pretty much long token which will be used further as header for other APIs to call in. So for this define a function what will be used as middlewear for other APIs.
Let’s create a file named auth.js. This function should be exportable to use it as middlewear wherever we will create our other APIs. Every time we would call an API with passing a header, which is formed as — “Bearer”+ token
const jwt = require('jsonwebtoken');module.exports = function verifytoken(req, res, next) {const authHeader = req.headers['authorization'] // it accepts token from header.const token = authHeader && authHeader.split(' ')[1] // omitting the bearer word and taking only token number.if (token == null) return res.sendStatus(401)jwt.verify(token, 'secret', (err, user) => {console.log(err)console.log(user);if (err) return res.sendStatus(403) // show status Forbidden.req.user = usernext() //if token is valid then proceed to next.})}
Now let’s call the API to show home page or dashboard using the middlewear function.
const auth = require("./auth.js");
app.post("/welcome", auth, (req, res) => {
res.status(200).send("Welcome to Employee Portal");
});
So, if token is valid user can access all other information according as a valid employee.
That’s all.