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

d4v1dv00 picture d4v1dv00 · Jun 17, 2011 · Viewed 13.5k times · Source

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:[email protected]/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.

Answer

maerics picture maerics · Jun 17, 2011

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.