Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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:[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.

like image 607
d4v1dv00 Avatar asked Jun 17 '11 16:06

d4v1dv00


2 Answers

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.

like image 57
maerics Avatar answered Sep 21 '22 14:09

maerics


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);
like image 44
gevorg Avatar answered Sep 23 '22 14:09

gevorg