NodeJS HTTP服务器 – 如何validation客户端的IP和login?

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

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

谢谢。

当一个客户端连接到你的HTTP服务器时,会发出' connection '事件,并且提供给callback函数的参数是一个types为net.Socket的stream,它具有一个名为' 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); 

至于通过URL中的embedded凭证validation,我不认为这种forms是可靠的,因为一些浏览器不传递 HTTP请求中的信息 (至lessIE和Chrome)。 您最好实施基于HTTP标准的authenticationscheme,如基本访问authentication或摘要访问authentication 。

对于HTTP基本/摘要式身份validation,您可以使用http-auth模块

 // Authentication module. var auth = require('http-auth'); var basic = auth.basic({ realm: "Simon Area.", file: __dirname + "/../data/users.htpasswd" // gevorg:gpass, Sarah:testpass ... }); // Creating new HTTP server. http.createServer(basic, function(req, res) { res.end("Welcome to private area - " + req.user + "!"); }).listen(1337); 
  1. 不要依赖IP。 他们很容易被欺骗。
  2. 对于基本的身份validation使用连接http://senchalabs.github.com/connect/middleware-basicAuth.html