Secure Authentication via JSON Web Tokens (JWT)

Creating an authentication process using JSON web Token with 3 layers of protection

shrey vijayvargiya
JavaScript in Plain English

--

Photo by Markus Winkler on Unsplash

JSON Web Token is 2 layers protected token generated using 3 succeeding process when joint altogether, those 3 processes are the parts of JSON Web Token as follows-

  • Header- The head part defined the algorithm used to create the token
  • Signature- The part to decode the token via signatures and depicts its authenticity.
  • Payload — By the virtue of name encapsulates any data required to send via token in 64base encoded secured form.

For more reference on How tokens are created and in-depth elucidation refers to the below link.

https://jwt.io/introduction

Overview

The idea behind this blog is to contribute an overview of How to work with JWT in the backend and create a process of authenticating the user.

  • I will be creating signup, login and decodeToken endpoints for users to our application.
  • Once a user is created or logged in successfully, provide the user with a JWT token created using the user email.
  • Every generated token has expired time and user data in its corresponding payload.
  • Once the user logged in, all other requests to our server should be made with this token present in the header.
  • Once the token is received in the header of the other API we will decode it to depict its authenticity.
  • Lastly, once the accorded token is the valid token, the user will be allowed to make a request to our servers.
Overview Flow Chart

Writing Code

I will start by setting a basic repository using express. Go ahead and install all the required packages we will be using.

yarn add express, body-parser, cors, nodemon, axiox, jsonwebtoken

After adding the packages create a basic route of logged in and signup in the routes folder inside the authRoutes.js file.

Basic routes of logged in and signup

Testing the routes by redirecting to the endpoint /login and /signup in the localhost port 3000.

Creating Token

The idea under the hood while generating a secured JWT token is to sign a token using a key and user email.

– The key we will be using is a manually added key by us and email will be the email id of the user-provided in the request of the API.

– We will be using the sign method of JWT to sign and generate our token.

jwt.sign({ email: email},process.env.JWTSecretKey,{expiresIn:'14d'})

– We are using email to sign the token because every user will have a unique email id to log in to our servers. No 2 users will have the same email id.

– Our token is generated using the user email id and the key. Here the key is JWTSecretKey — Please Note, this key should be added in the env file.

– Access the env files constants using dotenv npm package

– Add dotenv npm package and run the dotenv.config() in the root server.js

// Terminal 
yarn add dotenv
// server.js
const dotenv = require('dotenv');
dotenv.config();

– Using the process.env method you can grab all the constants from the .env file.

Sending Signed Tokens

We will send the token to the user in response to /login endpoint. We can also check the regular express of the email sent by the user and return an error back once the email is badly formatted.

login.js

In the response object of API we will send the token generated using JWT.sign() method. Do store this token in the frontend or in the database in the backend because we do need this token to make an API request to our servers.

Decoding Token

– To decode the token authenticity we again required the user email and the token.

– JWT itself provide a method called verify which accepts the token sent and JWTSecretKey from the env file as an argument.

– To add an extra security layer to your token we have signed out the token using the email of the corresponding user, so we will now check whether that email is present in the token or not followed by cross-checking that email with the user email sent in the request of the API.

– In this method, we have followed the following steps —

  • we first check the email and headers in the request body and header respectively.
  • Followed by checking the token validity using the jwt.verify() method
  • Another layer of protection is to check whether the decoded token payload contains the user email or not and cross-check the value with the email sent in the request body.

– In this way, we can check the authenticity of the user via tokens and once the user is the valid token we will allow the user to access our server and application.

– Below are the screenshots of the Postman desktop application of all the stages for the /decodeToken endpoint.

The left image is when no email is added and the right image is when no headers are given in request
Postman screenshot from the desktop.

Conclusion

This is the most secure way to check the user authenticity to accord his/her access to our servers. JWT itself is a very secure way using 2 layer security and we have added one 3rd layer using data in the payload of JWT to provide a more secured way to our servers. One last thing you can directly save these JWT tokens in the Cookie of the browser or sent the token from API in the cookie itself. This process has an advantage we just have to check the cookie in the browser and its validity in the Frontend application in order to allow the user to access the protected routes. If you want more detail on How to work with the token in Frontend I am adding the link to my article below.

https://medium.com/p/c60db33f1921?source=post_stats_page-------------------------------------

Until, next time. Have a good day, People.

Code => https://github.com/shreyvijayvargiya/iHateReadingLogs/tree/main/TechLogsBackend/GettingStartedWithJWT

More content at plainenglish.io

--

--