Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to fetch username and password from url using basic authentication in node.js? [duplicate]

I need to get the username and the password that a browser has send to my node.js application from the url.

I digged through various documentations and objects but I can't find anything useful. Does anybody know how to do that? Using Authentication header is not an option because modern bowsers don't set them.

https://username:[email protected]/
        =================
//         /\
//         ||
// I need this part

Thanks for your help!

like image 699
Stephan Avatar asked Oct 01 '14 16:10

Stephan


2 Answers

This method of authentication is called "Basic Auth". You can access username and password via basic-auth npm package using bellow code:

const express = require('express');
const basicAuth = require('basic-auth');
let app = express();
app.get('/', function (req, res) {
    let user = basicAuth(req);
    console.log(user.name); //prints username
    console.log(user.pass); //prints password
});
app.listen(3000, function () {});

Now if you send a request to http://username:password@localhost:3000/ this code will print your username and password in the console.

Be aware that this method of authentication is not supported in most of the browsers anymore.

like image 76
Seyed Ali Akhavani Avatar answered Sep 22 '22 23:09

Seyed Ali Akhavani


The username:password is contained in the Authorization header as a base64-encoded string:

http.createServer(function(req, res) {
  var header = req.headers['authorization'] || '',        // get the header
      token = header.split(/\s+/).pop()||'',            // and the encoded auth token
      auth = new Buffer(token, 'base64').toString(),    // convert from base64
      parts=auth.split(/:/),                          // split on colon
      username=parts[0],
      password=parts[1];

  res.writeHead(200,{'Content-Type':'text/plain'});
  res.end('username is "'+username+'" and password is "'+password+'"');

}).listen(1337,'127.0.0.1');

see this post: Basic HTTP authentication in Node.JS?

like image 40
Victor Avatar answered Sep 22 '22 23:09

Victor