41

I'm trying to send a cross-origin domain and adding a custom 'Authorization'-header. Please see the code below.

Error:

XMLHttpRequest cannot load {url}. Request header field Authorization is not allowed by Access-Control-Allow-Headers.

function loadJson(from, to) {
    $.ajax({
        //this is a 'cross-origin' domain
        url : "http://localhost:2180/api/index.php",
        dataType : 'json',
        data : { handler : "statistic", from : from, to : to
        },
        beforeSend : setHeader,
        success : function(data) {
            alert("success");
        },
        error : function(jqXHR, textStatus, errorThrown) {
            alert("error");
        }
    });
}

function getToken() {
    var cookie = Cookie.getCookie(cookieName);
    var auth = jQuery.parseJSON(cookie);
    var token = "Token " + auth.id + ":" + auth.key;
}

function setHeader(xhr) {
    xhr.setRequestHeader('Authorization', getToken());
}

I also tried:

headers : { 'Authorization' : getToken() },

in the ajax request.

Could it be that the jquery-ajax framework is blocking cross-origin Authentification? How can I fix this?

Update:

By the way: is there a safer method to store the auth.key on client-side then in a cookie? getToken() will be replaced with a more complex method, hashing the body, date,etc.

abatishchev
  • 98,240
  • 88
  • 296
  • 433
Johannes Staehlin
  • 3,680
  • 7
  • 36
  • 50

1 Answers1

67

This is an example of making a CORS request. If you have access to the server (which I assume you do since this is a request to localhost), you will need to add CORS-specific response headers. The simplest thing to do is to add the following response headers:

Access-Control-Allow-Origin: *
Access-Control-Allow-Methods: GET, POST, PUT, DELETE
Access-Control-Allow-Headers: Authorization

Your server also needs to be configured to respond to HTTP OPTIONS requests. You can learn more about making CORS requests here: http://www.html5rocks.com/en/tutorials/cors/

monsur
  • 45,581
  • 16
  • 101
  • 95
  • 3
    Well.. I forget the last of these three headers. I was just sending Origin and Methods. Stupid mistake. :) Yeah, I implemented OPTIONS. Good link! thanks – Johannes Staehlin Mar 05 '12 at 18:57
  • 1
    According to MDN the Access-Control-Allow-Origin header will need to be set to the origin when using credentialed requests instead of the wildcard. –  Jun 30 '15 at 15:03
  • 1
    @radicalmatt, Yea, he wrote it there too http://stackoverflow.com/a/15254158/632951 : *"The value `*` cannot be used for the Access-Control-Allow-Origin header when Access-Control-Allow-Credentials is true"* – Pacerier Jan 26 '16 at 19:47