Sunday, 16 April 2023

How to Implement JSON Web Tokens (JWTs) in a Node.js RESTful API

 This is a basic tutorial on how to implement JSON Web Tokens (JWT) in a Node.js application using the express framework. The tutorial assumes that you have basic knowledge of Node.js and how to create a Node.js application.





Part 1: Setup

1. Start by creating a new Node.js project by running the command npm init -y in your terminal. This will create a package.json file with default settings.

2. Install the required dependencies for the project by running the command 

npm i express jsonwebtoken dotenv. 

This will install the express framework, jsonwebtoken library for implementing JWT and dotenv library for loading environment variables from a .env file.

3. Create a .env file in the root directory of your project and add two variables ACCESS_TOKEN_SECRET and REFRESH_TOKEN_SECRET. These variables will be used to generate the secret key for signing the JWT.

4. Install nodemon as a development dependency by running the command npm i --save-dev nodemon. Nodemon is a tool that will automatically restart your server when you make changes to your code.

5. Create a new file named server.js. This will be the main file for your Node.js application.

6. Update the scripts section in your package.json file to add a new script for running the server with nodemon. Add "d": "nodemon server.js" to the scripts section.

7. Write the basic code to set up the express server in server.js. Define an array of objects to represent some example posts, and create a route to display all posts.

const express = require('express');

const app = express();

const posts = [

  { user: 'jin', title: 'a' },

  { user: 'kin', title: 'b' },

];

app.get('/posts', (req, res) => {

  res.json(posts);

});

app.listen(3000, () => {

  console.log('Server started on port 3000');

});


8. Create a new file named request.rest. This file will allow you to make REST requests to your API directly from your code editor using the Rest Client plugin. Update request.rest

Get http://localhost:3000/posts

Output: Click on send Request in request. rest to get the Data 




9. In the .env file, create two variables ACCESS_TOKEN_SECRET and REFRESH_TOKEN_SECRET with secret keys. 
You can generate a secret key using the crypto library by running the command require('crypto').randomBytes(64).toString('hex') in a new terminal.
  


Part 2: Get Access Token

10. Update the server.js code with the following code:

 //Allows to loading  .env file  into our process

require('dotenv').config()

const express=require('express')  //import express libray

const app =express() //set express server

const post=[{username:'jin',title:'a'},{username:'kin',title:'b'} ]//array of object with two post

app.get ('/posts',(req,res)=>{

res.json(post)

}) // create a route for all post

 

//JSON web Token implementation

//Create login Route to authenticate

//Create JSON web Token

const jwt = require('jsonwebtoken')

//pass JSON to app.get  we need to make sure server can handle it

 //This allow applicatio use JSON

//from the body that pass up  it inside request

app.use(express.json())

//post we want to create token that wahy post

 app.post ('/login',(req,res)=>{

 const u=req.body.username

 //normaly we authenticate here

 const user={name:u}

 //Implementation Of JSON web Token

 const accessToken=jwt.sign(user,process.env.ACCESS_TOKEN_SECRET)

 // payload what we want to serialize (user)

 //To serialize we need to secrete key created in the .env file  

 //accessToken has information saved inside of it

 res.json({accessToken:accessToken})

})

 app.listen(3000) // we want to listen to port 3000

 11. Update request.rest

 ###

Post http://localhost:3000/login

Content-Type: application/json

 

{

    "username":"kin"

    }

Output : Click on send Request in request. rest to Post  to get the access Token




Part 3: Get Data using Access Token 

12. Update the Get Request with Authentication as a Middle Ware

a.       Update request.rest

Get http://localhost:3000/posts

Authorization: Bearer eyJhbGciO

 


b.       Update the server.js file to include JWT authentication. Add a new route to handle user authentication and generate an access token.

        Authentication is a middleware and GET shows up by filtering request name

//Allows to loading  .env file  into our process

require('dotenv').config()

const express=require('express')  //import express libray

const app =express() //set express server

const post=[{username:'jin',title:'a'},{username:'kin',title:'b'} ]//array of object with two post

app.get ('/posts',authenticateToken,(req,res)=>{

res.json(post.filter(post=>post.username == req.user.name))

}) // create a route for all post

 //JSON web Token implementation

//Create login Route to authenticate

//Create JSON web Token

const jwt = require('jsonwebtoken')

//pass JSON to app.get  we need to make sure server can handle it

 //This allow applicatio use JSON

//from the body that pass up  it inside request

app.use(express.json())

//post we want to create token that wahy post

 app.post ('/login',(req,res)=>{

                                  const username=req.body.username

//normaly we authenticate here

const user={name:username}

//Implementation Of JSON web Token

const accessToken=jwt.sign(user,process.env.ACCESS_TOKEN_SECRET)

// payload what we want to serialize (user)

// to serialize we need secrete key created in .env file  

//accessToken has information saved inside of it

res.json({accessToken:accessToken})

})

 function authenticateToken(req,res,next){

//get authorization header

 const authHeader=req.headers['authorization']

//get the token part from Bearer Token  else undefined

const token= authHeader&& authHeader.split(' ')[1]

//incase of null token

if (token==null)return res.sendStatus(401)

//verify Token

//callback to Access token

jwt.verify(token,process.env.ACCESS_TOKEN_SECRET,(err,user)=>{

   //incase of error

    if(err)return res.sendStatus(403)

    req.user=user

    next()

})

}

app.listen(3000) // we want to listen to port 300


Output: Click on send Request in request. rest to get the data using  access Token



No comments:

Post a Comment