-1

So... i'm making a cross domain (CORS) call. When i initially make it on the page, it works just fine (noting that cross-domain issues aren't really a problem), but when i make another request later to the same server adding a bearer authorization token to the header, it is failing with a 401 Unauthorized.

Also, when i run this code from the same domain, both calls run successfully (identifying that the token is ok...)

Thoughts?

$.ajax({
  url: apiPath.userMetaUrl(),
  xhrFields: { 
    withCredentials: true 
  },
  cache: false,
  error: function (xhr, ajaxOptions, thrownError) {
    console.log("url: " + apiPath.userMetaUrl());
    console.log("fn loadUserMetaData xhr.status: " + xhr.status);
    console.log("fn loadUserMetaData xhr.responseText: " + xhr.responseText);
    console.log("fn loadUserMetaData thrownError: " + thrownError);
  },
  dataType: "json",
  jsonpCallback: "callback",
  beforeSend : setHeader,
  success: function (data) {
    //woohoo!
  }
}

function setHeader(xhr) {
  xhr.setRequestHeader('Authorization', 'Bearer ' + authenticatedInfo.access_token);
}

Again, running this code from same domain as apiPath.userMetaURL() works fine. On a different domain, the initial call without adding request header works fine. Access-Control-Allow-Orign has the cross-domain URL added. Access-Control-Allow-Headers has Authorization added. xhr.status returns 0 and responseText/thrownError are blank.

user2785146
  • 11
  • 1
  • 2

1 Answers1

1

JSONP != ajax

These requests you are making are simply adding <script> tags to your DOM. It's just wrapped in an ajax syntax for ease of use. You can't modify the request headers in this fashion. You need to create a CORS ajax request, and configure your server to handle them.

Executing jsonp requests on the same domain though... I believe jQuery just uses an xmlHttpRequest though. For cross-domain, it uses <script> tags. This would explain the behavior you are seeing.

Consider the following.

$.ajax({
    url: 'http://google.com', 
    dataType: 'jsonp', 
    beforeSend: function(xhr) { xhr.setRequestHeader('foo', 'bar'); }
});

Look at your network traffic. It will create the request, but you will not see the foo header.

Brad M
  • 7,857
  • 1
  • 23
  • 40
  • doesn't seem to make a difference. however, it does seem to be failing during the preflight OPTIONS request. looking into getting the server to allow unauthenticated OPTIONS requests since those won't carry request headers... – user2785146 Sep 17 '13 at 18:50
  • How would this *not* make a difference? It absolutely does, you just seem to have other issues. – Brad M Sep 18 '13 at 00:39
  • For the time I took researching your issues and providing at least a foundation, you could give some rep. – Brad M Sep 18 '13 at 17:46