跨域AJAX请求基本身份验证

10

我正在进行跨域AJAX请求以获取一些数据。REST服务使用IIS设置了基本认证

$.ajax({
            type: "GET",
            xhrFields: {
                withCredentials: true
            },
            dataType: "jsonp",
            contentType: "application/javascript",
            data: myData,
            async: false,
            crossDomain: true,
            url: "http://xx.xx.xx.xx/MyService/MyService.svc/GetData",
            success: function (jsonData) {
                console.log(jsonData);
            },
            error: function (request, textStatus, errorThrown) {
                console.log(request.responseText);
                console.log(textStatus);
                console.log(errorThrown);
            }
        });

当我发出这个请求时,它提示我输入凭据,我必须手动输入凭据才能获得响应。我们能否通过请求本身发送这些凭据?

3个回答

6

请按照以下代码格式传递用户名和密码:

$.ajax({
    type: "GET",
    xhrFields: {
        withCredentials: true
    },
    dataType: "jsonp",
    contentType: "application/javascript",
    data: myData,
    async: false,
    crossDomain: true,
    url: "http://xx.xx.xx.xx/MyService/MyService.svc/GetData",
    success: function (jsonData) {
        console.log(jsonData);
    },
    error: function (request, textStatus, errorThrown) {
        console.log(request.responseText);
        console.log(textStatus);
        console.log(errorThrown);
    }
    username: username,
    password: password,
});

5
$.ajax({  
    url: 'yoururl',
    username : username,
    password :password,
    type: 'POST',
    contentType: 'application/x-www-form-urlencoded',
    dataType: "text",
    xhrFields: 
    {
        withCredentials: true
    },
    beforeSend: function (xhr) { 
        xhr.setRequestHeader('Authorization', 'Basic ' + btoa(username + ":" + password));             
    }
});

2
我对这个答案并不感到兴奋,原因如下:它是冗余的(问题在半年前已经得到了回答),而且它是冗余的(据我所知,jQuery已经为您处理了身份验证等事项)。如果我对后者有误解,请编辑答案,我会删除此评论。 - Dave Newton
使用beforeSend属性对我很有用,因为由于某种原因,用户名和密码没有添加授权头。以防有所帮助。 - rodrigobartels

0
$.ajax({//No need to pass credentials 
            type: "get",
            async: false,
            url: "https://someurl/",
            xhrFields: {
                withCredentials: true
            },            
            success: function (data) {
                //do something
            }
        })

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接