简体   繁体   中英

nodejs - Allow request only if coming from the server ip

Is it possible to block a route if the request is not coming from the server? I have a http client installed on the server that makes a get request to a web service that I dont want to be public. The problem is that the http client is not logged in the application an is seen as an anonymous user by the server.

This is what I tried so far, but I dont know where in the req I should look for the ip of the requerer or if its the correct way to achieve what I want to do:

function isFromServer (req, res, next) {
    if(req.ip === '127.0.0.1') return next();
    else {
          var err = new Error('Not Found');
          err.status = 404;
          return next(err); 
    }
}    

//the webservice I want to allow only to the http client installed on the server
router.get('/[0-9]{3}$', isFromServer, function(req, res, next){
    var codecs = req.url.split('/')[1];
    res.render('metadata', {codecs: codecs});
});

From your syntax, I assume you are using Express. In that case, the straightforward way to get the client IP would be:

req.ip // → "127.0.0.1"

You can see the logic it uses, grabbing the first item from the array of proxy addresses req.ips when that array is constructed from the x-forwarded-for headers:

defineGetter(req, 'ip', function ip(){
    var trust = this.app.get('trust proxy fn');
    return proxyaddr(this, trust);
});

In case you aren't using express, try to use:

var ip = req.headers['x-forwarded-for'] 
    || req.connection.remoteAddress
    || req.socket.remoteAddress
    || req.connection.socket.remoteAddress;

This should take care for most configurations and works in a similar manner to Express's function above.

Sources:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM