XMLHttpRequest to send an HTTP GET request with username / password

I am developing Chrome using XMLHttpRequest to send an HTTP GET request with username / password to a URL with basic security, so that it can "automatically log in" afterwards (since Chrome caches credentials for HTTP basic -auth).

Here is the code I'm using:

var xml = new XMLHttpRequest(); xml.open('GET',<url>,false,<username>,<password>) xml.send(''); 

After some further research, I found out that this could be due to the fact that Chrome 19 does not support the username: pwd @url syntax for authentication to URLs with basic-auth protection, because when I send XMLHttpRequest, I see it in the Google Console Chrome js:

GET http: // user: pass@domain.com 401 (unauthorized)

Does anyone know if this is a bug or does Chrome stop supporting this feature?

My function

 function autoLogin(domain, user, password) { var httpAuth; if (window.XMLHttpRequest) { httpAuth = new XMLHttpRequest(); // code for IE7+, Firefox, Chrome, Opera, Safari } else if (window.ActiveXObject) { httpAuth = new ActiveXObject("Microsoft.XMLHTTP"); // code for IE6, IE5 } else { alert("Seu browser não suporta autenticação xml. Favor autenticar no popup!"); } var userName = domain + "\\" + user; httpAuth.open("GET", "/_layouts/settings.aspx", false, userName, password); httpAuth.onreadystatechange = function () { if (httpAuth.status == 401) { alert("Usuário e/ou senha inválidos."); eraseCookie('AutoLoginCookieUserControl_User'); eraseCookie('AutoLoginCookieUserControl_Password'); } else { if ($(".pnlLogin").is(':visible')) { $(".pnlLogin").hide(); $(".pnlUsuario").css("display", "block"); $(".avatar").css("display", "block"); var name = $().SPServices.SPGetCurrentUser({ fieldName: "Title" }); $(".loginNomeUsuario").html("Seja Bem Vindo(a) <br />" + name); } } } var userAgent = navigator.userAgent.toLowerCase(); $.browser.chrome = /chrome/.test(navigator.userAgent.toLowerCase()); if ($.browser.chrome == true) { httpAuth.setRequestHeader("Authorization", "Basic " + btoa(userName + ":" + password)); } try { httpAuth.send(); } catch (err) { console.log(err); } } 
+4
source share
1 answer

You need to add headers to the XHR request manually.

xml.setRequestHeader ("Authorization", "Basic" + btoa (username + ":" + password))

Demo here: http://jsbin.com/inuhiv/2 (NOte, there is nothing to find out, however look at devtools and see that the request has an auth header)

enter image description here

+12
source

Source: https://habr.com/ru/post/1490991/


All Articles