Sign in
Log inSign up
Introduction To JWT Authentication

Introduction To JWT Authentication

Rishabh kunwar's photo
Rishabh kunwar
·Aug 15, 2021·

5 min read

Hello guys, today I gonna talk about the basics of Authentication via JSON web token. I love to understand any concept with help of real-life examples or analogies, so here I am going to give the example which I used to understand this.

Before starting, just imagine you are in a college. Let's Start...

Signing a Token

So consider you have taken admission into the college and received your college Identity Card. This is basically signing a token, your Identity Card will be unique and will have only your data, now whenever you want to enter college you need to possess your card otherwise you will not be allowed to enter (trust me guys I have faced it 😅)

So when a user signs up on your app, they get registered, and when they log into your app via their credentials they will receive a token, a JSON web token, which is unique for every user and will have the data of the specific user, it may be user's id or anything you want but remember never put any sensitive data like password, etc

now enough analogy and theory show me how to sign a token

before using JWT you need to install the package

$ npm install jsonwebtoken

after installing you need to import the package in your code

let jwt = require('jsonwebtoken');

there are many ways in which you can sign a token, this is the most simple way to do it

const token = jwt.sign({data: 'userData'}, 'secret', { expiresIn: '24h' });

let's break down the above code,

jwt.sign():- is a function provided by the package you installed above it is used to generate the token

{data: 'userData'}:- this is basically where you will provide the user data, when the token will be decoded you will get this data, don't worry decoding part is later in the blog

' secret':- This is nothing but a randomly generated key that will be used to generate the token, you can put any string here but the bigger it will be the more strong the token will be.

you can generate the key by putting the below code into your command prompt or terminal

node -e "console.log(require('crypto').randomBytes(256).toString('base64'));"

(remember to put your key in .env file)

token variable will receive the actual token which was signed and generated and it will be sent to the frontend of your app.

{ expiresIn: '24h' }:- As it says it basically gives the token validity, here it means the token generated will have its validity for 24 hours and after that, it will be useless

with this, I come to my next point that is...

Verifying the Token

remember you received your Identity Card, now whenever you try to enter your college premises there will be a person on the gate who will check and verify your card, your college security guard, and trust me guys even if you are very good friend with them, even if they know you very well, still, when you try to enter your college they will pretend like they haven't seen you before. E8ERNw.gif

ever faced this betrayal 😅😅 ?

Verification works the same way, the token you have signed above will be verified successfully till 24 hours after creation, but it will fail to verify the same token even after a minute passed after it. now let's understand why this thing happens, remember the { expiresIn: '24h' } this basically gives a life span or validity to the token after the time period ends the token is useless.

here is the code which verifies the token

try {
  let decoded = jwt.verify(token, 'secret');
  //do something
} catch(err) {
  // err(send a 404 error)
}

now let's break the above code

jwt.verify():- is a function provided the package which you have installed this is like the security guard which will check and verify the token it receives.

token:- This is the actual token which we will get from the frontend.

'secret':- This is the same key that you have used while signing the token.

when the token is verified successfully we will get an object with the creation and the expiry time of the token and the user data which we have used while signing and then you can use the data accordingly.

But what if token verification failed...

Failed Verification and 404 redirects

When your Identity Card will not be verified successfully by the guard?

  • When the time period of that card will be over

The validity of an ID card is year wise or semester wise, so when you go to next year or next semester you receive a new Identity Card from the college, and the old one is then useless it basically is expired, and you can't use the old card to enter the college same thing happens here when the token is expired user need to get the new token to use your app and will be redirected to get it.

  • When you try to show someone else's card to enter

If you try to use someone else's card to enter college, the guard will catch you and you will have a morning session with your HOD or any faculty member (and it really sucks) same things happen here if a user uses someone else's token or give a wrong secret the token will not be verified. But instead of the morning session with faculty/HOD users will be redirected to get a new token

this redirection is called 404 redirects

Remember the code snippet from the above section in that in catch section I have written a comment send 404 error. 404 is a status code that is been sent when authentication fails, on frontend we will check if the status code is 404 which here means token verification failed, and then we will redirect the user to the login page because remember when a user logs in a new token will be signed and then he can use your app again till the new token will get expired, This is called 404 redirects. for redirects, you can add an Axios interceptor which will check the status code and redirect the users

This is how JWT Authentication or basically Authentication works, I hope my analogy didn't confuse you 😅

So with this, I come to the end of the blog, This is the first time I am writing a blog please share your views it will help me to learn and grow