JWT(jsonwebtoken) Token Based Authentication using nodeJS.

Onkar Shingate
Geek Culture
Published in
5 min readJul 1, 2021

First, we have to know what is JWT? JWT(jsonwebtoken) is npm package which is used to create token when user log-in into our application.

  • the basic structure of token is as below:-
JWT token structure
  • Header:- Header in JWT token contains some metadata about the token. we as users don't have to write anything into it.
  • Payload:- Payload is the information that we have to add to the token for any further use.
  • Signature:- Signature is the URLencoded text which is made using Header, Payload, and Secret available in the server. the same secret is to be used to extract information from tokens in the future. The Secret is used so that only authorized servers can only decode Token.

Now let us see how we can use tokens in the server.

Step 1:- Installing JWT and setting registration part.

  • First, we have to install the jsonwebtoken package into our express application using the following code.
npm i jsonwetoken --save
  • Now, we have to handle the registration part of our application. this part is explained in my previous blog. for further reference see the image below.
  • now we have to handle the “/users/register” route.
handling registration part

Step2:- Handling login route

Step 3:- Creating Token

  • For creating the token, we have to add createToken() method into our User model.

Tip:- while creating createToken() don’t use arrow function. as we have to use this keyword which will not work with arrow function.

  • First we have to create payload object and add the data which we need to add inside token for future use.
  • now we have to import jsonwebtoken into our User model at the top inside variable jwt.
let jwt = require('jsonwebtoken');
  • now, we can use jwt.sign() method to create a token that will accept payload as the first argument and Secret as the second argument.

Tip:- Remember to add secret into .env file and use dotenv package to keep your Secret a secret.

  • once the token is created return the token.
createToken()

Step4:- Returning token where we called createtoken().

  • remember where we called createToken() . which was while handling “/users/login” route.
  • now we have created token inside variable named token.
  • now, we can use this as token as we like. for now we are returning token and user data .
handling /users/login route

Step 5:- using the token to authenticate.

  • Now, we have a token and we have to use it while protecting routes by only allowing the logged users to access them.
  • This can be achieved by using tokens. Tokens can be used to find information about logged users.
  • In React we can pass tokens directly while accessing routes but for now, we are going to use the POSTMAN application to send tokens into headers while requesting routes.
  • In the POSTMAN application, we have to create a new field named “Authorization” inside headers and as a value, we have to paste a token.
using postman to send tokens.

step 6:- Creating auth.js file into middlewares folder

  • Now, we have to create an auth.js file inside a folder named middlewares.
  • Now, we have to write a method named isLoggedIn() inside the auth.js file.
  • First, import jsonwebtoken at top of the file.
  • Now, inside the isLoggedIn() we can have access to a token that is sent by a POSTMAN app by accessing req.headers.
  • If there is no token, then we can send an error message to the user.
  • And if there is a token we can use jwt.verify() method, which accepts token as the first argument and Secret as the second argument.
  • jwt.verify() method returns payload inside token as a result.
  • Once we have payload now we can put it to req.user and call next() method. due to this information inside payload is available to the next middleware.
isLoggedIn() inside auth.js file

Step 7:- Using the “isLoggedIn()” method inside the auth.js file when we need authorization.

  • For any route if we need to protect it from the users which were not logged in we can use isLoggedIn() method.
  • Suppose we have to protect route “/profiles/:profileName” from the users which are not logged in.
  • we can add auth.isLoggedIn middleware while handling routes as below.
using auth.isLoggedIn middleware
  • Once we add this middleware only logged users can see the proper response and the non-logged user will get an error message as “you need to log in”.
  • And one more feature of this is we have access to logged user information which is present in the req.user object.

--

--