d4v1dv00 d4v1dv00 - 3 months ago 7x
Node.js Question

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?



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 ----^

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.