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?
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.
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.
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