Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unable to decode base64 from req.header.authorization

In express I am grabbing the basic auth from:

req.headers.authorization

From that I get back

dXNlcm5hbWU6cGFzc3dvcmQ=

I say "hey that looks like base64". I quickly go to one of those base64 sites and decode it and it turns out to be 'username:password'. So I google how to decode base64 in express 4. I wind up with this code:

console.log(new Buffer(req.headers.authorization.toString(), 'base64').toString('ascii'));

That is returning:

+"qUMI95iAMM]=I

Which is not username:password. I also tried this with the utf8 setting and that did not work either. I also tried this without toString() on the req.headers.authorization. How do I properly decode base64 with expressjs?

like image 294
Johnston Avatar asked Aug 22 '15 15:08

Johnston


2 Answers

In case anyone is as stupid as I am and didn't realize that the string that is returned from req.headers.authorization is the word Basic followed by the base64 encoded string, you must split the string before decoding.

console.log(new Buffer(req.headers.authorization.split(" ")[1], 'base64').toString())

req.headers.authorization returned for me: Basic dXNlcm5hbWU6cGFzc3dvcmQ=. Not just the base64 string.

like image 86
Johnston Avatar answered Sep 24 '22 06:09

Johnston


Using the new Buffer API it is now

console.log(Buffer.from(req.headers.authorization.split(" ")[1], 'base64').toString())

Else you will get deprecated warnings.

like image 22
Sam Avatar answered Sep 22 '22 06:09

Sam