Home > other >  Middleware to protect an endpoint in express
Middleware to protect an endpoint in express

Time:07-17

I wrote a middleware function that should protect one of my endpoints. I want to allow only a few ip addresses to call that endpoint. This is the middleware:

const ipAddressCheck = async (req, res, next) => {
    const ip = req.socket.remoteAddress;

    console.log(`IP address caller: ${ip}`);

    if(['ip-allowed'].includes(ip)) {
        next();
    } else {
        return res.status(401).json({
            message: 'ERROR: UNAUTHORIZED'
        })
    }
}

Is this way to proceed secure? Or is there any other way that is considered safer? This endpoint creates an appcheck token that let my colleagues call the secured endpoints.

CodePudding user response:

In general, I would recommend doing it in the load-balancing/reverse-proxy level (NGINX or something else).

In case you are having trouble/want keeping it at the app level: Need to pay attention that if you indeed use LB you will need to specify to pass the IP address (since you will always get the IP of the LB).

If all the above are not relevant what you have done seems ok, can also be done with req.headers['x-forwarded-for']

Hope it helps :)

  • Related