简体   繁体   中英

NodeJS HTTP Server - How To Verify Client's IP and Login?

If I decide to use http module for my server, which module/method(s) I need to do the following?

  • To Verify the source IP address of connecting client?
  • If the server requires the URL like http://username:password@exmaple.com/method1 , how do i setup the Http server of NodeJS to accept such authentication and how do i verify the credentials provided from the client's connection?

Thanks.

When a client connects to your HTTP server the ' connection ' event is emitted and the argument provided to the callback is a stream of type net.Socket which has an attribute called ' remoteAddress '. Similarly, each HTTP request passed to your request listener also has a reference to the connection object:

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

As for authentication via embedded credentials in the URL, I don't think this form is reliable as some web browsers do not pass on the information in the HTTP request (IE and Chrome at least). You're better off implementing an HTTP standards-based authentication scheme such as Basic access auth or Digest access auth .

For HTTP Basic/Digest authentication you can use http-auth module

// 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. Do not rely on IPs. They are easily spoofed.
  2. For basic auth use Connect with http://senchalabs.github.com/connect/middleware-basicAuth.html

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM