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
});
-
-
Save ivermac/922def70ed9eaf83799b68ab1a587595 to your computer and use it in GitHub Desktop.
Note that above doesn't estabilish a browser session. It only works for that one request.
This however does work:
var http = new XMLHttpRequest(); http.open("get", 'https://httpbin.org/basic-auth/', false, login, pass); http.send(""); if (http.status == 200) { alert("OK. You now established a session. You can navigate to the URL."); } else { alert("⚠️ Authentication failed."); }
@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, using fetch
, all code snippets, used the method of doing headers.set('Authorization', 'Basic ' + btoa(username + ":" + password));
and using the headers with fetch
.
With sending username
and password
using headers.set
, I was getting a 401
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.
@Eccenux, Thanks, you helped me a lot!
"btoa is not defined" when this code gets used in a Node14 lambda on AWS.
Thanks @Eccenux, I've learnt something new!