Movatterモバイル変換


[0]ホーム

URL:


Skip to content
DEV Community
Log in Create account

DEV Community

Cover image for JWT explained with project
Anuj Singh
Anuj Singh

Posted on • Edited on

     

JWT explained with project

My Portfolio ||My other blogs ||Linkedin Account

What is JWT ?

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 theHMAC algorithm) or a public/private key pair usingRSA orECDSA.

When should you use JSON Web Tokens?

  • Authorization
  • Information Exchange

What is the JSON Web Token structure?

In its compact form, JSON Web Tokens consist of three parts separated by dots (.), which are:

  • Header
  • Payload
  • Signature

Therefore, a JWT typically looks like the following.

xxxxx.yyyyy.zzzzz

jwt

JWT In-Depth Knowledge
JWT Playground

To Run the application :

You should have installednodeJS andpostman andMongoDB in your machine.
We will be using postman to test our application. You can use any front-end for the same.
Also make sure mongoDb is installed correctly.

  • Clone the project
    git clone https://github.com/singhanuj620/probackend_jwt

  • Install NPM dependencies
    npm install

  • Run the server
    npm run start

  • Register a User first.
    http://localhost:4000/register
    to register a user. Format will be as follows :

register
Congratulations !!! User is successfully saved in database.

  • Login with existing user to check jwt workinghttp://localhost:4000/loginto logina user. Format will be as follows :

login
Congratulations !!! User is successfully logged into application.

You can now access theSECRET ROUTEhttp://localhost:4000/dashboard

Since we have done with using the application, Now let's understand howJWT is working in background. 🙌🙌🙌

Working of JWT in this application

We are using a popular jwt library for encoding and decoding of token. For more info visitJWT NPMJS
And to encrypt the password we are usingbCryptJS

We will be using jwt in this flow :

  1. First user is registered into database
  2. User is going to login, and that's where anew token is generated specific for this user
  3. This genrated token is saved into cookies, so that accessing the SECRET route, this jwt token is checked for the confirmation.
  4. BINGOOOOOOO !!!!

When User is going to login

We are going to find the user from database and validate password using bCryptJS, and is everything is okay, then we are going to generate a new token using the jsonwebtoken library.

It has 3 parameters :

  1. what data you want to encode in this token, here i want to encode an object having 2 key i.e user_id and email.
  2. A secret key which can be any random string
  3. Time when this token is going to expires, in this case i have allocated 2 hour lifespan of this token.
consttoken=jwt.sign({user_id:user._id,email},process.env.SECRET_KEY,{expiresIn:"2h"});
Enter fullscreen modeExit fullscreen mode

and then pass/save this token into cookies to front-end. We are usingcookie-parser npm library to do this work.

constoptions={expires:newDate(Date.now()+3*24*60*60*1000),httpOnly:true}res.status(200).cookie('token',token,options).json({success:true,token,user});
Enter fullscreen modeExit fullscreen mode

Okay so now user is logged in, but how should be validate that the token which is generated is authorized user and he/she is requesting to access the SECRET route is allowed ? 🙄🙄🙄

Validating JWT token 💥💥💥

When logged in user tries to access the SECRET route i.e in our case/dashboard then, a middlewareauth is going to validate the token.

For that backend has to fetch the token which is set in cookies when user was login.

Note For those who don't know what's middleware.Middleware is just a check between 2 item. If check is okay, proceed to next operation, otherwise return back from there. Imagine it just likewatchman 😂.

Everytime when anyone tries to access theSECRET route, thisauth middleware will check that if that request has token in cookie or not (only logged in user will have token in cookie). If not, return back.

If token is there in cookie, it will check that token is authentic or not.
HOW ? 🙄🙄
Remember that secret key which was just a random string, yes that will help to decode the token and fetch the data which was encoded into token.

WHICH DATA? 🙄🙄
Remember user_id and email 😉😉

And if everything is good, proceed to the next operation 💯

try{constdecode=jwt.verify(token,process.env.SECRET_KEY);req.user=decode;}catch(err){returnres.status(403).send("Invalid Token")}returnnext();
Enter fullscreen modeExit fullscreen mode

What we have learned ?

  1. What are JWT
  2. How to run this github repo application
  3. How to genrate JWT token
  4. How to validate JWT Token

Thank You 🤗 💥🤩

Top comments(0)

Subscribe
pic
Create template

Templates let you quickly answer FAQs or store snippets for re-use.

Dismiss

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment'spermalink.

For further actions, you may consider blocking this person and/orreporting abuse

anujsingh.net | ReactJS frontend professional with 3+ YOE. NextJS, MERN Stack, Redux, Graphql
  • Location
    Bangalore, India
  • Education
    Pranveer Singh Institute of Technology
  • Work
    ReactJS Web Developer | Programmer
  • Joined

More fromAnuj Singh

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

Log in Create account

[8]ページ先頭

©2009-2025 Movatter.jp