Wednesday, September 19, 2018

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

Leave a Comment

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:password@myurl.com/         ================= //         /\ //         || // I need this part 

Thanks for your help!

6 Answers

Answers 1

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 may not be supported in some browsers.

Answers 2

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?

Answers 3

This is exactly what you're looking for:

http://nodejs.org/api/url.html

If you want to know where to get the URL itself from, it is passed in the request object, also known as "path":

Node.js: get path from the request

Answers 4

/createserver/:username/:password  let params={ userName:req.params.username, password:req.params.password } console.log(params); 

Is this is what you wanted .?

Answers 5

The http://username:password@example.com format is no longer supported by either IE or Chrome, wouldn't be surprised if others followed suit if they haven't already.

(From T.J. Crowder comment here)

Answers 6

the URL is accessible by the server in the request object :

http.createServer(function(req, res) {     var url = req.url     console.log(url) //echoes https://username:password@myurl.com/     //do something with url }).listen(8081,'127.0.0.1'); 
If You Enjoyed This, Take 5 Seconds To Share It

0 comments:

Post a Comment