Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery.Ajax "Access to restricted URI denied" explanation?

I'm investigating cross-domain usage of a .NET WCF Domain Service from a local (file:// access) html app. The app is using jQuery for AJAX calls.

Without authentication (i.e. with anonymous authentication) on the server I have successfully retrieved data in JSON format with the CORS "Access-Control-Allow-Origin: *" header in place and in JSONP format without the header.

Now I'm trying to understand the behaviour when authentication and the CORS header is in place with JSON (not JSONP) format data.

The following jQuery code will send a request to the server, which in turn responds with "HTTP/1.1 401 Unauthorized".

$.ajax({
    url: myUrl,
    dataType: 'json',
    cache: false,
    complete: function () { /* do stuff */ },
    timeout: 5000,
    data: myData
});

The following jQuery code does not make a request to the server and immediately throws an exception "Access to restricted URI denied", code 1012.

$.ajax({
    url: myUrl,
    dataType: 'json',
    cache: false,
    complete: function () { /* do stuff */ },
    timeout: 5000,
    username: "chris",
    password: "password",
    data: myData
});

I understand and expect the first case. Can anyone explain to me the exception in the second case? I would have expected the request to be made at least.

Edit: Grrr, this is in FF 10.0.2. Chrome seems to act as I expect, so is this a FF issue?

like image 627
Chris Avatar asked Feb 28 '12 09:02

Chris


Video Answer


1 Answers

If you use credentials such as cookies or HTTP basic auth username/password fields in your cross-origin request, you need to also set the "withCredentials" flag on the XHR to true. In jQuery, this is done with the xhrFields property on the $.ajax call. Change your code to read

$.ajax({
    url: myUrl,
    dataType: 'json',
    cache: false,
    complete: function () { /* do stuff */ },
    timeout: 5000,
    username: "chris",
    password: "password",
    data: myData,
    xhrFields: { withCredentials: true }
});

Also, the server on the other end can't use "*" for the Access-Control-Allow-Origin header with credentials. It instead has to provide an exact match for the Origin header sent to it.

like image 120
Ben Combee Avatar answered Sep 19 '22 13:09

Ben Combee