Skip to content

nodejs jwt

Vijay Pratap edited this page Jul 20, 2024 · 2 revisions

JWT - JSON Web Token

Table of Contents

  1. About JWT
  2. Implementation of JWT

1. About JWT

1.1 What is JWT

  • Definition: JSON Web Token (JWT) is a secure way to send information between two parties.
  • Structure:
    • Header: Contains the token type (JWT) and the signing algorithm.
    • Payload: Contains the data (claims).
    • Signature: Ensures the token hasn't been altered and verifies the sender.

1.2 Use Cases of JWT

  • Authentication: Allows users to access routes and services after logging in.
  • Authorization: Defines user roles and permissions.
  • Information Exchange: Securely transfers data between parties, ensuring integrity and authenticity.

2. Implementation of JWT

2.1 Setup Fresh NodeJS Project

mkdir jwt-demo
cd jwt-demo
npm init -y

2.2 Install Packages expressjs, jsonwebtoken

npm install express jsonwebtoken

2.3 Create Sample Route

Create a file named server.js and add the following code:

const express = require('express');
const jwt = require('jsonwebtoken');

const app = express();
app.use(express.json());

const APP_PORT = 3000;

app.get('/', (req, res) => {
    try {
        res.status(200).send({ message: 'Welcome to JWT Demo!' });
    } catch (error) {
        res.status(500).send({ message: error.message })
    }
});

app.listen(APP_PORT, () => {
    console.log(`Server running on http://localhost:${APP_PORT}`);
});

2.4 Generate JWT Token

Add the following route to generate a JWT token:

const generateToken = (payload) => {
    try {
        const token = jwt.sign(payload, 'your_secret_key', { expiresIn: '1h' });
        return token
    } catch (error) {
        res.status(500).send({ message: error.message })
    }
}

app.post('/login', (req, res) => {
    try {
        const { email, password } = req.body;
        const token = generateToken({ email, password })
        res.json({ token });
        res.status(200).send({ message: "User Loggedin Successfully!" })
    } catch (error) {
        res.status(500).send({ message: error.message })
    }
});

2.5 Verify JWT Token

Add a middleware to verify the JWT token:

const verifyToken = (req, res, next) => {
    try {
        const token = req.headers['authorization'];
        if (token == null) return res.status(401).json({ message: "Authorization token not provided!" });

        jwt.verify(token, 'your_secret_key', (err, user) => {
            if (err) return res.status(403).json({ message: "Invalid provided authorization token!" });
            req.user = user;
            next();
        });
    } catch (error) {
        res.status(500).send({ message: error.message })
    }
};

app.get('/profile', verifyToken, (req, res) => {
    try {
        res.status(200).send({ message: "Profile Get Successfully!", data: { email: req.user.email } });
    } catch (error) {
        res.status(500).send({ message: error.message })
    }
});

Complete Code Example

Here is the complete code combining all steps:

const express = require('express');
const jwt = require('jsonwebtoken');

const app = express();
app.use(express.json());

const APP_PORT = 3000

const generateToken = (payload) => {
    try {
        const token = jwt.sign(payload, 'your_secret_key', { expiresIn: '1h' });
        return token
    } catch (error) {
        res.status(500).send({ message: error.message })
    }
}

const verifyToken = (req, res, next) => {
    try {
        const token = req.headers['authorization'];
        if (token == null) return res.status(401).json({ message: "Authorization token not provided!" });

        jwt.verify(token, 'your_secret_key', (err, user) => {
            if (err) return res.status(403).json({ message: "Invalid provided authorization token!" });
            req.user = user;
            next();
        });
    } catch (error) {
        res.status(500).send({ message: error.message })
    }
};

app.get('/', (req, res) => {
    try {
        res.status(200).send({ message: 'Welcome to JWT Demo!' });
    } catch (error) {
        res.status(500).send({ message: error.message })
    }
});

app.post('/login', (req, res) => {
    try {
        const { email, password } = req.body;
        const token = generateToken({ email, password })
        res.json({ token });
        res.status(200).send({ message: "User Loggedin Successfully!" })
    } catch (error) {
        res.status(500).send({ message: error.message })
    }
});

app.get('/profile', verifyToken, (req, res) => {
    try {
        res.status(200).send({ message: "Profile Get Successfully!", data: { email: req.user.email } });
    } catch (error) {
        res.status(500).send({ message: error.message })
    }
});

app.listen(APP_PORT, () => {
    console.log(`Server running on http://localhost:${APP_PORT}`);
});