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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With