如何使用basic-auth-connect和express获取用户IP

时间:2016-03-25 22:28:21

标签: node.js express basic-authentication http-authentication

我有一个简单的节点应用程序,使用 express basic-auth-connect 运行Web服务器。

我知道我可以使用类似

之类的东西在app.get(...)上获取客户端IP地址
  

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

但如果http身份验证失败,它就不会到达::

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'));
});

1 个答案:

答案 0 :(得分:0)

刚刚找到一个简单的解决方案,我在auth之前添加了另一个快速中间件:

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