JWT Authentication in Nodejs

jwt authentication

In today’s digital world, security plays an important role in protecting user data and safe interactions between clients and servers. JWT (JSON Web Token) authentication has emerged as the best method for implementing secure authentication in web applications. This article will explore the concept of JWT Authentication in Nodejs and provide a step-by-step guide to implementing it.

Introduction

JWT is an open standard (RFC 7519) that defines a compact and self-contained method for securely transmitting information between parties as a JSON object. It consists of three parts: a header, a payload, and a signature. The header contains metadata about the token, the payload carries the claims, and the signature verifies the authenticity of the token.

How it works

  1. Client Authentication:
    The client sends their credentials (e.g., username and password) to the server.

  2. Token Generation:
    The server verifies the credentials and generates a JWT containing the necessary user information and a secret key.

  3. Token Transmission:
    The server sends the JWT back to the client.

  4. Request Authorization:
    The client includes the JWT in the header of subsequent requests.

  5. Token Verification:
    The server verifies the signature and decodes the JWT to extract the user information.

Implementation – JWT Authentication in Nodejs

Before we start we need to focus on the previous article in which we learn about the API in nodejs
we will implement the JWT in that APIs with good folder structures and follow the best practices.

Installing required packages

npm install express jsonwebtoken

Adding key in Environment File

JWTSECRET = NODEJSPROJECT

Creating Folders

Create a folder name Services and create a new file in it and name as JWTService.js and paste this code or follow the below screenshot.

import dotenv from 'dotenv';
dotenv.config();
import jwt from 'jsonwebtoken'

class JWTService {
    static sign(payload, expiry = '1y', secret = process.env.JWTSECRET) {
        return jwt.sign(payload, secret, { expiresIn: expiry })
    }
    static verify(token, secret = process.env.JWTSECRET) {
        return jwt.verify(token, secret);
    }
}

export default JWTService;

Creating Middlewares

Create a new file name as Authentication.js in the middleware folder and paste this code or follow the below screenshot.

import JWTService from "../Services/JWTService";
const Authentication = async (req, res, next) => {
    //Get Headers form client side
    let AuthHeader = req.headers.authorization;
    
    if (!AuthHeader)
        return res.json({ status: 400, message: "Invalid authorization" });
    //Split the Token
    const Token = AuthHeader.split(' ')[1];
    try {
        //Verify The Token
        const { _id } = await JWTService.verify(Token);
        req.user = {};
        req.user._id = _id;
        next();
    }
    catch (err) {
        return res.json({ status: 400, message: "Invalid authorization Token" });
    }
}



export default Authentication;

Importing in Routes

In the previous article, we create a route to get all users let’s implement JWT in that Routes, open your UserRoutes.js and modify the code or follow the below screenshot.

import Authentication from '../Middlewares/Authentication';

router.get('/user', Authentication, UserController.getUsers);

Hit the EndPoint

Now everything is done let’s hit the endpoint

Your endpoint will be “​​http://localhost:4000/api/user”;

When you hit this endpoint or browser or Postman then it will give me the response code 400 because you have not passed the Token in API.

How to Get Token

Now the question is from where we will get the token. The token will be provided when we will log in the user.

Change the UserRegister Controller

Now go to UserController and create a new function for the login user and define its routes or paste this code in UserController

async loginUser(req, res, next) {
        try {
            const response = await UserModel.findOne({ UserEmail: req.body.UserEmail, Password: req.body.Password });
            if (response) {
                const accessToken = JWTService.sign({ _id: response._id });
                return res.json({ status: 200, data: response, accessToken });
            }
            else {
                return res.json({ status: 404 });
            }
        }
        catch (Err) {
            console.log(Err)
        }
    }
jwt authentication

Changes in Routes

Paste this code in UserRoutes or follow the bellow screenshot.

router.post('/login/user',UserController.loginUser);
jwt authentication

After this hit the user login endpoint and it will send an access token in response, follow the below screenshot.

jwt authentication

After this now you can hit the get all user routes and pass the token in Header following the bellow screenshot.

jwt authentication
jwt authentication

Now Everything is done.

If you have any doubts you can comment or follow the video for the same

Conclusion – JWT Authentication in NodeJS

JWT authentication provides a secure and efficient way to implement authentication in Node.js applications. Remember to implement proper security measures, handle token expiration, and follow best practices to maximize.

Read More
https://scribblersden.com/quick-sort/

https://www.linkedin.com/company/scribblers-den/
https://www.facebook.com/scribblersden.blogs

Thank You

Related Post

Leave a Reply

Your email address will not be published. Required fields are marked *