jQuery基本身份验证不起作用

jQuery basic authentication doesn't working

本文关键字:不起作用 身份验证 jQuery      更新时间:2023-09-26

我需要向使用基本身份验证的服务器发出CORS请求。我使用jQuery 1.5.1,代码如下:

$.ajax({
    type: 'GET',
    global: true,
    url: theSource,
    crossDomain: true,
    beforeSend: function(xhr) { 
        xhr.withCredentials = true;
        xhr.setRequestHeader("Authorization", "Basic " + btoa("username:password"));
    },
    error: function (xhr, status, errorThrown) {
        alert(errorThrown + ''n' + status + ''n' + xhr.statusText);
    },
    success: function (data) {
        ABC.ABCconsole.log('Success');
        ABC.openAjaxSuccess(data);
    }
});

在服务器端设置这些标头:

Access-Control-Allow-Credentials: true
Access-Control-Allow-Headers: Authorization, Accept
Access-Control-Allow-Methods: GET, POST, PUT, DELETE
Access-Control-Allow-Origin: http://example.com

不幸的是,在服务器的响应我有401 Unauthorized错误。

请求我有这些头:

Accept:*/*
Accept-Encoding:gzip,deflate,sdch
Accept-Language:de-DE,de;q=0.8,en-US;q=0.6,en;q=0.4
Connection:keep-alive
Host:example01.com
Origin:http://example.com
Referer:http://example.com/france/asd/qwes/business-nothing.html
User-Agent:Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/35.0.1916.153 Safari/537.36

响应中,这些标头:

Access-Control-Allow-Credentials: true
Access-Control-Allow-Headers: Authorization, Accept
Access-Control-Allow-Methods: GET, POST, PUT, DELETE
Access-Control-Allow-Origin: http://example.com
Content-Length:58
Content-Type:text/html
Date:Wed, 16 Jul 2014 09:42:00 GMT
Server:Microsoft-IIS/7.5
Set-Cookie:loc=phl;path=/;
WWW-Authenticate:Basic realm="example01.com"

你知道为什么会这样吗?

UPD:正如您在请求中看到的,我没有看到我的Authentication头被设置。如果我用--disable-web-security键运行浏览器,一切都很好。Authentication头设置正确

UPD2: http POST方法请求失败。那么问题就在这里?

Remote Address:111.111.11.12:80
Request URL:http://example01.com/asst/index.epx?id=569fe9d0-1515-423a-bae8-84265b6396a0&_=1405506291028
Request Method:OPTIONS
Status Code:401 Unauthorized

使用Access-Control-Allow-Origin: *