Creating a JWT Token With NodeJS

Creating a JWT Token With NodeJS

What is JWT?

JSON Web Token is a proposed Internet standard for creating data with optional signature and/or optional encryption whose payload holds JSON that asserts some claims. The tokens are signed either using a private secret or a public/private key.

Prerequisite:-

  • NodeJs

  • POSTMAN

  • Basic cmd Commands

  • JavaScript Intermediate

  • And 5 minutes of your time :-)

Steps To Follow:-

  1. Make Fresh NodeJS App

  2. Make Package JSON

  3. Install Express and JWT Token

  4. Make Simple API

  5. Make Login with JWT

  6. Make Profile API with JWT Token

  7. Complete Code

  8. Bonus for readers

Make Fresh NodeJs App

Let's start by creating a folder specified for our project within our local system.

Name it: - Node-jwt-ex

Open Your folder with the VS Code by copy-Pasting the path link of your project folder into the vs code Then install the react within your project following this:-
Click on Terminal > New Terminal

Make Package JSON

In the cmd prompt Firstly, type npm init this will help us to initialize our project. Then enter your project name in our case we are keeping it as jwt-ex same name as our folder. Then keep entering until the last step, we can find out the package.json file had been created on the left side of the visuals code project screen.

Install Express and JWT Token

Installing Express can be achieved without expressJS too but in this case, we will have to write a lot of code so to reduce your effort we are using expressJS in our case as creating the project within the core NodeJs is a bit longer or can be a difficult process.

Open :- Terminal < New Terminal

Enter :- npm i jsonwebtoken

Also to check whether the packages had been successfully installed within your project you can check it within the package.json file where both of the packages can be found within the dependencies.

Moving ahead create a new file within the project by the name of index.js and this file will consist of all the codes Now the very first which we will do is import the expressJS within this file which can be achieved by the below code.

//index.js
const express = require("express")

Then we will do the importing of jwt which can be achieved by the below code.

//index.js
const jwt = require("jsonwebtoken");

Moving ahead we will create an app that will be part of the express by the below code.

//index.js
const App = express();

Make Simple API

Let's just create a small API by which we can check out whether everything is working fine or not. but the testing can only be achieved if you have prior knowledge of POSTMAN methods or application knowledge

//index.js
app.get("/",(req,resp) =>{
     resp.json({
        message: "Hey,I am working fine"
     })
})

within GET, we have passed two functions req and resp and within the JSON we passed our response.
Within it, we haven't used the JWT Token yet which we can fetch from POSTMAN. But let's just wait a while we will create it soon.

Let's just create one more API to handle the post method
we are creating a sample user here

//index.js
app.post("/login",(req,resp)=>{
   const.user={
       id:1,
       username:"Pallav"
       email: "pallav@test.com"
   }                                                
})

The app. listen() function is used to bind and listen to the connections on the specified host and port. This method is identical to Node’s http.Server.listen() method. The app returned by express() is a JavaScript function, designed to be passed to Node’s HTTP servers as a callback to handle requests.

Port:5000 is where our application can be viewed within it we will pass our function which we want to show on our running app console.

Now, As you know that we had already imported JWT in our project we would be using the same now within our App.post API method

//index.js
jwt.sign({user},secretKey, {expiresIn : '300s'}, (err, token) => {
         resp.json({
            token
         })
})

jwt.sign is the function within which we can pass different parameters in our case we are using the user detail which will help us to generate tokens.

Then we need to initialize a secretkey. Let's just create the constant of the secret key in the top architecture of our index.js file

Then We need to initialize its expiring date. Later on, we will use the callback function within which we will use two things first error if in case error commences then we will use a token. within it, we will pass our resp function and then pass your token.

Let's just create a function now to verify the token

//index.js
function verifyToken(req,resp,next)

we will pass three parameters within our newly created function req,resp, and next. in our case the next will work as a middleware. for more info about the middleware you can refer to the below link

Middleware-Wikepedia

but before moving we will create one more API which is named by as to access the profile

Make Profile API with JWT Token

we will create one profile API which will be used to access the profile by using the below code

//index.js
app.post("/profile",(verifyToken,(req,resp))=>{
   const.user={
       id:1,
       username:"Pallav"
       email: "pallav@test.com"
   }                                                
})

But there is a catch here how will the verifyToken Will verify our token this can be done by using postman

Let us just get to the POSTMAN.

Postman > Enter the URL - https://localhost:5000/profile > header > Enter The key - "Authorization" > within key - enter the token which was generated earlier but before that on the top of the token just add "bearer" in the prefix of the token.

Moving ahead we have to create a function by the name of verifyToken and then we will GET it within the JWT Token. as we had used authorization so we will pass that from the request header. Then we will check whether it is undefined or not. by using the If condition. Else we will send the response by showing the output result.

//index.js
function verifyToken(req,resp,next){
const bearerHeader = req.headers['authorization'];
if(typeof bearerHeader !== 'undefined') {
const bearer = bearerHeader.split(" ");                //split will be done based on space so that we can GET the second bearer 
const token=bearer[1];    // we had accessed the second array of which token we wanted
req.token = token;
next();                                      //next function will help us to  inject the controll of verifyToken function within the profile   
}else{
   resp.send({
      result:'Token is not valid'
   })
}
}

By Now we had received the token moving ahead to verifyToken we will be going back to the previous part of POST API.

//index.js
app.post("/profile",verfyToken,(req,resp)=>{
    jwt.verfy(req.token,secretKey,(err,authData)=>{
         if(err){
           response.send({result:"Invalid Token"})
           } else {
             resp.json({
               message: "profile accessed",
               authData
             })
           }
    })
})

If you are reading it until here. Congrats mate you learned a great thing today which is useful in every tech stack. If you found any difficulties following along please do reach out if would be more than happy to connect with you also you can find the complete source code below and just after that, I have a small bonus reading for you to check out.
Keep Learning :-)

//index.js (Complete Source Code)
const express = required('express');
const jwt = require("jsonwebtoken");
const app = express();
const secretKey="secretKey";

app.get("/",req,resp) => {
  resp.json({
        message:"Sample API"
    })
})

app.post("/login",(req,resp)=>{
    const user={
      id:1,
      username:"Pallav",
      email: "pallav@test.com"
    }

    jwt.sign({user},secretkey,{expiresIn:'300s'},(err,token)=>{
        resp.json({
          token
        })
    })
})

app.listen(5000,()=>{
  console.log("app is running on 5000 port")
});

app.post("/profile",verifyToken,(req,resp)=>{
  jwt.verify(req.token,secretkey,(err,authData)=>{
      if(err){
        resp.send({result: "invalid token"})
      }
      else{
        resp.json({
          message:"profile accessed",
          authData
        })
      }
  })
})

function verifyToken(req,resp,next){
const bearerHeader = req.header['authorization'];
if(typeof bearheader ! = undefined){
const bearer = bearerHeader.split(" ");
const token= bearer[1];
req.token= token;
next();
}else{
   resp.send()
     result : "Invalid token"
}
}

Bonus Reading

Test the post API request within the postman

First, run the node Module again by typing node .\index.js within the cmd then the open postman Enter your URL within the post Method In our case it is

https://localhost:5000/login

after testing our URL within the postmen you will get the token generated within the body now as the token is generated and in case we want to access the profile section of the website we need to achieve it by creating a function that will help him to verify the token.