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,

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

Install JWT Package

Use the below command for install json webtoken

>> npm install jsonwebtoken 1 >> 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'); 1 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

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 1 eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9 . eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ . SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c

Header

Header part will include the ALGORITHM & TOKEN TYPE

eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9

Decoded Header { "alg": "HS256", "typ": "JWT" } 1 2 3 4 5 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" } 1 2 3 4 5 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) ) 1 2 3 4 5 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 1 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" }); }); }); 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 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" } 1 2 3 4 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.

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!" }); }}; 1 2 3 4 5 6 7 8 9 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!" }); }); }); 1 2 3 4 5 6 7 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,

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