At Agira, Technology Simplified, Innovation Delivered, and Empowering Business is what we are passionate about. We always strive to build solutions that boost your productivity.

,

How To Secure Node.js RESTful APIs With JSON Web Tokens

  • By Manigandan
  • September 18, 2018
  • 2449 Views

 

What Is JSON Web Token?

JSON Web Token (JWT) is an open standard (RFC 7519) that defines a compact and self-contained way for securely transmitting information between parties as a JSON object. This information can be verified and trusted because it is digitally signed. JWTs can be signed using a secret (with the HMAC algorithm) or a public/private key pair using RSA or ECDSA. So this JSON Web tokens will greatly help us to secure the Node.js REST API.

When Should You Use JSON Web Tokens?

Here are some scenarios where JSON Web Tokens are useful:
Authorization: This common scenario for using JWT. Once the user is logged in, each subsequent request will include the JWT, allowing the user to access routes, services, and resources that are permitted with that token. Single Sign On is a feature that widely uses JWT nowadays, because of its small overhead and its ability to be easily used across different domains.
Information Exchange: JSON Web Tokens is the great way of securely transmitting information between parties. Because JWTs can be signed—for example, using public/private key pairs—you can check and verify the sender’s.Additionally, we can we calculate the signature using the header and payload, you can also verify that the content hasn’t been tampered with.
In this blog I will describe the how to use the JSON web token using JWT with nodeJS.
The following three steps we require for this process,

  1. Install JWT package
  2. Configure JWT in your APP
  3. How to Check JWT token for GET & POST API.

 

Install JWT Package

Use the below command for install json webtoken

>> npm install jsonwebtoken

 

Configure JWT In Your APP

After installing the jsonwebtoken, we need to include the package in js file. For example, i have kept the file name here like user.js file here. Similarly you can name the file as you wish and include the below code in it.

var jwt = require('jsonwebtoken');

 
Now the jwt is a ‘jsonwebtoken variable , we used this variable to generate the secure web token for RESTful API.

How To Check JWT Token for GET & POST API

API Structure
This process will help us to check whether the request we get or post are from authorized person or not.
JWT token have three different combination encoded data, as you can see below

eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c

 

Header

Header part will include the ALGORITHM & TOKEN TYPE
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9

Decoded Header
{
 "alg": "HS256",
 "typ": "JWT"
}

 

Payload

Our Encrypted original data will be included in this Payload section,
eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ

Decoded Data
{
 "email": "abc@gmail.com",
 "name": "mani"
}

Verifying Signature

This would be the most significant part in securing JWT token which will have the encoded token that will decide to accept or reject the custom signature
SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c

Decoded signature

 

HMACSHA256(
 base64UrlEncode(header) + "." +
 base64UrlEncode(payload),  
 Your-256-bit-secret (secret_word)
)

So as i shown above, the encoded link will look like this,

eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c

 

Generating Token For Login

Login request  (/login) – POST

router.post("/login", (req, res, next) => {
 let fetchedUser;
 User.findOne({ email: req.body.email })
   .then(user => {
     if (!user) {
       return res.status(401).json({
         message: "Auth failed"
       });
     }
     fetchedUser = user;
     return bcrypt.compare(req.body.password, user.password);
   })
   .then(result => {
     if (!result) {
       return res.status(401).json({
         message: "Auth failed"
       });
     }
     const token = jwt.sign(
       { email: fetchedUser.email, userId: fetchedUser._id },
       "secret_word",
       { expiresIn: "1h" }
     );
     res.status(200).json({
       token: token,
       expiresIn: 3600
     });
   })
   .catch(err => {
     return res.status(401).json({
       message: "Auth failed"
     });
   });
});

 

const token = jwt.sign(
       { email: fetchedUser.email, userId: fetchedUser._id },
       "secret_word",
       { expiresIn: "1h" }

Here you can see how i have added the token, secret word and also the declared amount of time it should expire. So this token will only be valid until the allocated time left after that it will not be valid.

Login POST

 

How To check The Token Is Valid Or Not

Create separate js file and add the below code which will act as the Middleware for checking the token validity. For example, i have named as check-auth.js

const jwt = require("jsonwebtoken");
module.exports = (req, res, next) => {
 try {
   const token = req.headers.authorization.split(" ")[1];
   jwt.verify(token, "secret_word");
   next();
 } catch (error) {
   res.status(401).json({ message: "Auth failed!" });
 }};

The requested token should be verified then & there before applying any process, For example, Here am about to the delete the record so before that am verifying the requested token using checkAuth middleware.

const checkAuth = require("/check-auth");
router.delete("/:id", checkAuth, (req, res, next) => {
 Post.deleteOne({ _id: req.params.id }).then(result => {
   console.log(result);
   res.status(200).json({ message: "Post deleted!" });
 });
});

 

Request Without Token

If any request processed without request then it will get failed,
Delete-fail

Request with token, 


We’re done! now you have seen the process of generating and validating the JSON web token to secure the Node.js RESTful API.
Now it’s your turn to secure your RESTFUL API with JSON web token and start doing and post us your queries, we’re glad to help you out. Similarly If you wish to read more? then never miss out anything from  our largest blog portal where you can get continuous blog updates & latest posts about all latest technologies which would be perfect for your 15 minutes tea break! And in case if you’re a newbie then don’t forget to subscribe us to get the latest updates from diverse technologies. Hit the subscribe link  and start getting the frequent updates from us straight to your inbox.
For more inquires reach us via info@agiratech.com

Manigandan

An ideal Full Stack Developer, having around 5+ years of experience in web development arena, expertise in AngularJS, Nodejs, PHP and also scoring 6 years of experience in Networking & Window servers. A perfect all-rounder has fondness to play diverse role. he always strives to match perfection and likely remains the best in whatever role he takes.