简体   繁体   中英

Jquery + CORS+ Basic Auth with Access-Control-Allow-Origin header: No 'Access-Control-Allow-Origin' header is present on the requested resource

I'm having trouble to make a simple GET request with Basic Auth to one of my CORS enabled web server with jQuery.

The problem seems to be linked to Basic Auth since when I deactivate it on my server, the request works correctly . However, with Basic Auth enabled, it fails with 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 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

I added the OPTIONS method to return a response with 4 headers : Access-Control-Allow-Origin: * , Access-Control-Allow-Method: POST, GET, PUT, UPDATE, OPTIONS , Access-Control-Allow-Headers: Content-Type, Authorization, Accept, X-Requested-With and Access-Control-Allow-Credentials:true .

and added the Access-Control-Allow-Origin: * header to all responses.

I also tried to make the OPTIONS request with Postman and I can see the CORS headers:

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 → *

I also tried to set Access-Control-Allow-Origin: localhost:80 instead of * but the result was the same.

my javascript code is the following:

$.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) {
})

My server is a simple java webapp with Jersey running on Tomcat7.

How can I solve this issue?

Thanks!

Try to set the headers in 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) {
});

Access-Control-Allow-Origin: * is your problem. You can't use wildcards in this header when doing authenticated requests. Instead, explicitly set Access-Control-Allow-Origin to the value from the request's Origin header.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM