5

I develop a Chrome uses XMLHttpRequest to send a GET HTTP request with an username/password to a basic-auth-protected URL, so that it can then "auto-login" to it afterwards (since Chrome caches credentials for HTTP basic-auth).

Here's the code I use:

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

After some additional research, I found out that it might have to do with Chrome 19 not supporting the username:pwd@url syntax for authenticating to basic-auth protected URLs, because when I send the XMLHttpRequest, I see this in Google Chrome's js console:

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

Does anyone know whether it's a bug or if Chrome stopped 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

1 回答 1

14

您需要手动将标头添加到 XHR 请求。

xml.setRequestHeader("授权", "基本" + btoa(用户名 + ":" + 密码))

演示在这里: http: //jsbin.com/inuhiv/2(注意,没有什么要验证的,但是看看 devtools 并看到请求有 auth 标头)

在此处输入图像描述

于 2013-07-12T09:08:54.767 回答