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!
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.
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?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With