let username = 'john';
let password = 'doe';
let url = `https://httpbin.org/basic-auth/${username}/${password}`
let authString = `${username}:${password}`
let headers = new Headers();
headers.set('Authorization', 'Basic ' + btoa(authString))
fetch(url,{method: 'GET', headers: headers})
.then(function (response) {
console.log (response)
return response
});
Created
August 1, 2018 14:45
-
-
Save ivermac/922def70ed9eaf83799b68ab1a587595 to your computer and use it in GitHub Desktop.
Using fetch with basic auth
@Eccenux, Thanks, you helped me a lot!
"btoa is not defined" when this code gets used in a Node14 lambda on AWS.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@Eccenux Thank you so much for this. This is a life saver. For the past 2-3 days I've been trying to figure out how to logout a user that is logged in using HTTP Basic Authentication.
Though basic authentication does not support logout, after some research I found that there are a few hacks which can be used.
One such hack involved creating a button and sending wrong credentials using an xhr request.
I decided to use
fetch
because that's easier to use. However when I searched for a method to send username and password for basic authentication, usingfetch
, all code snippets, used the method of doingheaders.set('Authorization', 'Basic ' + btoa(username + ":" + password));
and using the headers withfetch
.With sending
username
andpassword
usingheaders.set
, I was getting a401
response (unauthorized user) for that particular request, however for the website, as a whole, the user was not getting logged out.Your code snippet helped tremendously in not only providing a solution that works but also providing an explanation as to why using the
headers.set
method appeared to be working but was not working.