通过 IP 地址限制对基于 Node.js 的 HTTP 服务器的访问
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12349251/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Restrict access to Node.js-based HTTP server by IP address
提问by Vitalii Maslianok
How can I restrict access by IP address in a Node.js HTTP server application?
如何在 Node.js HTTP 服务器应用程序中通过 IP 地址限制访问?
I'm looking for something like this:
我正在寻找这样的东西:
Deny from all
Allow from ..
I need to allow access to the site for only a few IP addresses. How can I do this?
我只需要允许几个 IP 地址访问该站点。我怎样才能做到这一点?
回答by Alex K
I'm not sure how bulletproof is this approach, but here it is, collected from answers around the web:
我不确定这种方法的防弹能力如何,但它是从网络上的答案中收集的:
var http = require('http');
http.createServer(function (req, res)
{
var ip = req.ip || req.connection.remoteAddress || req.socket.remoteAddress || req.connection.socket.remoteAddress;
if (ip == '127.0.0.1') // exit if it's a particular ip
res.end();
...
Please, someone more proficient in node - correct me
请更精通节点的人 - 纠正我
回答by Brad
If you are restricting access to the entire serverby network address, it is best to put those rules in your firewall. If you want to handle it at the application layer for some reason (ease of configuration, dynamic authorization, etc.) then it is best to do this immediately upon connection rather than waiting for an HTTP request.
如果您通过网络地址限制对整个服务器的访问,最好将这些规则放在您的防火墙中。如果您出于某种原因(易于配置、动态授权等)想在应用程序层处理它,那么最好在连接时立即执行此操作,而不是等待 HTTP 请求。
Node.js' http.Server emits a connectioneventwhich you can use to determine the remote address and kill the connection before (or during) the actual HTTP request. This code is untested but should get you started:
Node.js 的http.Server 发出一个connection事件,您可以使用它来确定远程地址并在实际 HTTP 请求之前(或期间)终止连接。此代码未经测试,但应该可以帮助您入门:
var server = http.createServer(function (req, res) {
// Your normal request handling goes here
});
server.on('connection', function (sock) {
console.log(sock.remoteAddress);
// Put your logic for what to do next based on that remote address here
});
server.listen(80);

