Securing Node.js APIs: Client IP Authorization with Nginx and Middleware
Published: 2023-12-08 14:19:48

In this tutorial, we'll explore how to enhance the security of your Node.js APIs by implementing IP authorization. We'll cover the steps to configure Nginx to include the X-Forwarded-For header and create a middleware in Node.js to check client IP addresses against a whitelist.

## **Prerequisites**

Before we begin, ensure that you have the following:

- A Node.js project with APIs

- Nginx installed on your server

- Basic knowledge of Nginx configuration


## Step 1: Update Nginx Configuration
Open your Nginx configuration file, typically located at /etc/nginx/sites-available/default, and add the X-Forwarded-For header to the proxy configuration:

```
server {
    listen 80;
    listen [::]:80;
    server_name your_server_ip;

    location / {
        proxy_pass http://127.0.0.1:5000;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection 'upgrade';
        proxy_set_header Host $host;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;  # Add this line
        proxy_cache_bypass $http_upgrade;
    }

    # Additional configurations if needed
}
```

This modification ensures that the client's IP address is forwarded to your Node.js application.

## Step 2: Create IP Authorization Middleware
Next, create a middleware in your Node.js project to check client IP addresses against a predefined whitelist. In a file named ipAuthorizationMiddleware.js:

```
// ipAuthorizationMiddleware.js
const allowedIPs = ['your_static_ipv4_addresses'];  // Add your static IPv4 addresses here

exports.ipAuthorizationMiddleware = (req, res, next) => {
  const clientIp = req.headers['x-forwarded-for'];

  if (allowedIPs.includes(clientIp)) {
    return next();
  } else {
    return res.status(403).json({
      error: "Access denied",
      message: "Your IP address is not allowed",
    });
  }
};
```

Replace 'your_static_ipv4_address' with your actual static IPv4 address.

## Step 3: Apply Middleware to Routes
Integrate the middleware into your routes. In your main application file (e.g., app.js), apply the middleware to the desired routes:

```
// app.js
const express = require('express');
const { ipAuthorizationMiddleware } = require('./ipAuthorizationMiddleware');

const app = express();

// Apply the middleware to the desired routes
app.use('/api/admin', ipAuthorizationMiddleware);

// Define your routes below
// ...
// Or you can also add this middleware only to certain routes individually in your route.js file

// Start the server
const port = process.env.PORT || 5000;
app.listen(port, () => {
  console.log(`Server is running on port ${port}`);
});
```

Replace /api/admin with the path where you want to enforce IP authorization.

## Conclusion
By updating your Nginx configuration to include the X-Forwarded-For header and implementing a middleware in your Node.js application with a statically defined whitelist, you can add an extra layer of security to your APIs. Only requests from the specified static IP address will be allowed, enhancing the overall security of your system.

Feel free to adapt this guide to fit your specific project requirements. Happy coding!