Blog | G5 Cyber Security

Node.js Authentication Middleware

TL;DR

This guide shows you how to create authentication middleware in Node.js using Express. This middleware checks if a user is logged in before allowing access to protected routes.

Prerequisites

Step 1: Install Required Packages

If you haven’t already, install the necessary packages. We’ll use jsonwebtoken for creating and verifying tokens.

npm install jsonwebtoken express

Step 2: Create a Secret Key

You need a secret key to sign your JSON Web Tokens (JWTs). Important: Keep this key secure! Don’t hardcode it directly into your code in production. Use environment variables instead.

const jwtSecret = 'your-super-secret-key'; // Replace with a strong, random string

Step 3: Implement the Authentication Middleware

This middleware function will verify the user’s token. It checks for a token in the Authorization header.

function authenticate(req, res, next) {
  const authHeader = req.headers['authorization'];

  if (!authHeader) {
    return res.status(401).send('No token provided');
  }

  const token = authHeader.split(' ')[1]; // Bearer 

  jwt.verify(token, jwtSecret, (err, user) => {
    if (err) {
      return res.status(403).send('Invalid token');
    }

    req.user = user;
    next(); // Pass control to the next middleware/route handler
  });
}

Explanation:

Step 4: Apply Middleware to Protected Routes

Now you can use your authentication middleware to protect specific routes.

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

// ... (your other route definitions)

app.get('/protected', authenticate, (req, res) => {
  res.send(`Welcome to the protected route, ${req.user.username}!`);
});

Explanation:

Step 5: Example Token Creation (for testing)

This shows how you might create a token after successful login.

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

  const user = { username: 'testuser' }; // Replace with actual user data

  jwt.sign(user, jwtSecret, { expiresIn: '1h' }, (err, token) => {
    if (err) {
      return res.status(500).send('Token creation failed');
    }
    res.send({ token });
  });
});

Explanation:

Exit mobile version