NodeJS HTTP Server - 如何验证客户端的IP和登录?

d4v*_*v00 10 http-authentication node.js

如果我决定为我的服务器使用http模块,我需要执行以下哪些模块/方法?

  • 验证连接客户端的源IP地址?
  • 如果服务器需要http:// username:password@exmaple.com/method1这样的URL ,我如何设置NodeJS的Http服务器以接受此类身份验证,以及如何验证客户端连接提供的凭据?

谢谢.

mae*_*ics 19

当客户端连接到您的HTTP服务器时,将connection发出' '事件,并且提供给回调的参数是net.Socket具有名为' remoteAddress' 的属性的类型的流.同样,传递给请求侦听器的每个HTTP请求也都有对连接对象的引用:

var http = require('http');
var server = http.createServer(function (req, res) {
  res.writeHead(200, {'Content-Type': 'text/plain'});
  res.end('Hello ' + req.connection.remoteAddress + '!');
  // Client address in request -----^
});
server.on('connection', function(sock) {
  console.log('Client connected from ' + sock.remoteAddress);
  // Client address at time of connection ----^
});
server.listen(9797);
Run Code Online (Sandbox Code Playgroud)

对于通过URL中的嵌入式凭据进行身份验证,我认为这种形式不可靠,因为某些Web浏览器不会传递 HTTP请求中的信息(至少IE和Chrome).您最好实现基于HTTP标准的身份验证方案,例如基本访问身份验证摘要访问身份验证.