0

I have this simple node app running a web server using express and basic-auth-connect .

I know that I can get the client IP address on app.get(...) using something like

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

But if the http authentication fails it doesn't get there ::

var express = require('express');
var app = express();
var basicAuth = require('basic-auth-connect');

app.set('port', (process.env.PORT || 5000));

app.use(basicAuth(function(user, pass){ 
    authState = 'someUserName' == user && 'somePassword' == pass;
    console.log(user, pass, authState);

    // NEED the IP here ...         

    return authState;
}));

app.get('*', function(req, res) {
    var ip = req.headers['x-forwarded-for'] || req.connection.remoteAddress;
    console.log(ip);

    res.sendFile(__dirname + '/');
});

app.listen(app.get('port'), function() {
    console.log('Node app is running on port', app.get('port'));
});
tibbus
  • 4,168
  • 2
  • 20
  • 33
  • you can get it using express only; http://stackoverflow.com/questions/10849687/express-js-how-to-get-remote-client-address – Joe Tannoury Mar 25 '16 at 22:46

1 Answers1

0

Just found a simple solution, I added another express middleware before auth :

app.use(function (req, res, next) {
    var ip = req.headers['x-forwarded-for'] || req.connection.remoteAddress;
    console.log(ip);
    next();
});
tibbus
  • 4,168
  • 2
  • 20
  • 33
  • This solution has a race condition if you use that IP in another middleware callback because another request might come before your basic auth function runs. I'd just make a wrapper that calls the basicAuth function after getting the IP. Perhaps that's what you meant. good luck. – Gidon Wise May 27 '19 at 12:21