无法使用ajax发送授权标头

时间:2016-08-04 15:34:19

标签: jquery ajax wcf authorization

以下是我发送请求的功能:

function invokeService() {
        $(document).ready(function() {
                var user = "User1";
                var pass = "Pwd1";


        var hash_str=make_base_auth(user, pass);

        // the post to your webservice or page
        $.ajax({
            method: "GET",
            xhrFields: {
                withCredentials: true
            },
            beforeSend: function (xhr) {
                        xhr.setRequestHeader('Authorization', hash_str);
                },
            headers: {
                'Authorization': 'Basic ' + hash_str
            },
            url: "http://Servername/ProjName/TestService.svc/GetDetails/" + $('#itemid').val(),
            contentType: "application/json; charset=utf-8",
            dataType: "jsonp"



        }); 
    });
}

我尝试过不同的方法,直接通过以下方式传递用户名和密码:

$.ajax({
    method: "GET",
    username: user,
    password: pass,
    ...
});

并通过设置授权标头,但我在Fiddler中检查它,在请求的Auth部分中,它指出“没有授权标头”。它只是不发送它。任何人都可以帮我修改我的授权标题吗?

以下是Fiddler在请求标题中显示的内容:

GET /projName/TestService.svc/GetDetails/ABC123?callback=jsonpxxxxxxxxxxxxx HTTP/1.1


Client
Accept: application/javascript, */*;q=0.8
Accept-Encoding: gzip, deflate
Accept-Language: en-US
User-Agent: Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; WOW64; Trident/5.0)

Transport
Connection: Keep-Alive
Host: ServerName

1 个答案:

答案 0 :(得分:0)

我使用它并且工作正常(beforeSend回调的相关部分):

 beforeSend: function (xhr) {
                        xhr.setRequestHeader ("Authorization", "Basic " + btoa(username + ":" + password));
                }

btoa 会在标头中对您的敏感数据进行编码。

希望它有所帮助。