带有Access-Control-Allow-Origin标头的Jquery + CORS + Basic Auth:请求的资源

时间:2015-05-18 07:28:27

标签: javascript jquery jersey cors basic-authentication

我很难用Basic Auth向我的一个支持CORS的Web服务器用jQuery做一个简单的GET请求。

问题似乎与Basic Auth有关,因为当我在服务器上停用它时,请求正常工作。但是,启用基本身份验证后,它会失败并显示No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost' is therefore not allowed access. The response had HTTP status code 401

我添加了OPTIONS方法以返回包含4个标题的响应Access-Control-Allow-Origin: *Access-Control-Allow-Method: POST, GET, PUT, UPDATE, OPTIONSAccess-Control-Allow-Headers: Content-Type, Authorization, Accept, X-Requested-WithAccess-Control-Allow-Credentials:true

并将Access-Control-Allow-Origin: *标题添加到所有回复中。

我还尝试使用Postman发出OPTIONS请求,我可以看到CORS标题:

Access-Control-Allow-Credentials → true Access-Control-Allow-Headers → Content-Type, Authorization, Accept, X-Requested-With Access-Control-Allow-Methods → POST, GET, PUT, UPDATE, OPTIONS Access-Control-Allow-Origin → *

我还尝试设置Access-Control-Allow-Origin: localhost:80而不是*,但结果是一样的。

我的javascript代码如下:

$.ajax({
url: this.host,
type: "GET",
data: {
    something: "something"
},
headers: {
    "Authorization": "Basic " + this.credentials,
    "Accept": "application/json"
},
cache: false
}).done(function (data, textStatus, xhr) {
}).fail(function (xhr, textStatus) {
})

我的服务器是一个简单的java webapp,在Tomcat7上运行Jersey。

我该如何解决这个问题?

谢谢!

2 个答案:

答案 0 :(得分:0)

尝试在beforeSend中设置标题:

var that = this;
$.ajax({
  url: this.host,
  type: "GET",
  data: {
    something: "something"
  },
  beforeSend: function (xhr) {
    xhr.setRequestHeader("Authorization", "Basic " + that.credentials);
  },
  cache: false
}).done(function (data, textStatus, xhr) {
}).fail(function (xhr, textStatus) {
});

答案 1 :(得分:0)

Access-Control-Allow-Origin:*是您的问题。在进行经过身份验证的请求时,您无法在此标头中使用通配符。相反,将Access-Control-Allow-Origin显式设置为请求的Origin标头中的值。