How in node.js to limit access on ip?
It is necessary to allow access to the site for only a few ip. But how to do it - I can not find anywhere.
Thanks in advance to all who responded!
How in node.js to limit access on ip?
It is necessary to allow access to the site for only a few ip. But how to do it - I can not find anywhere.
Thanks in advance to all who responded!
If I understood correctly, then somehow (not tested)
var http = require('http'); function createHttpServerForIps( ips, isProxy, onAllowed, onNotAllowed ) { return http.createServer(function( request, response ) { function getIp() { return isProxy ? request.headers['x-forwarded-for'] || : request.connection.remoteAddress; } function ipAllowed( ip ) { var allowed = false; for( var i=0; i<ips.length; ++i ) { if( ip === ips[i] ) { allowed = true; break; } } return allowed; } ipAllowed( getIp() ) ? onAllowed( request, response ) : onNotAllowed( request, response ); }); } var isProxy = false; createHttpServerForIps([ '123.123.123.133', '344.344.344.344' ], isProxy, function( request, response ) { // ... allowed }, function( request, response ) { // ... not allowed } ).listen(8000);
In the case of a match (the first callback), your logic works, in case of an error (the second callback), you can either give 403 or break the connection stupidly, you decide.
remoteAddress == nginxAddress
, then take ip from the X-Real-IP
header. - Ilya PirogovThey got IP ( req.connection.remoteAddress
), compared it with the list, if not allowed - they dropped the client in response according to RFC status 403 Forbidden
.
Source: https://ru.stackoverflow.com/questions/144478/
All Articles