IE 11, XMLHttpRequest, and CORS - ajax

I'm trying to access an API service (via XMLHttpRequest/ajax) hosted on a sub-domain (ie: a client on app.samedomain.com will call out to api.samedomain.com) that requires specific headers to be set for security purposes, but I keep getting Access is denied errors. All the solutions I've found say the client/end user must add the site to the "Trusted Sites" security zone, but obviously this is not a real solution. What do I need to do to access an external site with specific headers?
Example Code:
var getUserById = function (user, callback, error) {
$.support.cors = true;
var endpoint = _getApiVersion() + '/person/model/' + user.userId;
var _headers = _setHeaders(endpoint, null, user, 'GET');
$.ajax({
type: 'GET',
beforeSend: function (request)
{
request.setRequestHeader("api-key", _headers['api-key']);
request.setRequestHeader("timestamp", _headers['timestamp']);
request.setRequestHeader("content-md5", _headers['content-md5']);
request.setRequestHeader("content-type", _headers['content-type']);
request.setRequestHeader("signature", _headers['signature']);
request.setRequestHeader("Access-Control-Allow-Origin", "*");
},
url: _getBaseUrl() + endpoint,
data: null,
contentType: 'application/json',
dataType: 'json',
success: callback,
error: error
});
};
Thanks in advance,
Dan

Are you trying to get data that is not in the same domain as the requester? If that is the case the only option is to proxy the original request via a service so XMLHttpRequest has access to it.

"Access-Control-Allow-Origin" is a response header, not a request header. It is something that the server should send back to IE as part of the response.
If that still doesn't work, you might want to try firing up the F12 Network tool in the IE Dev tools to see if you can get more detail into where in the process the request is failing (Ex: It might be failing on a CORS preflight OPTIONS request).
Also, Rather than using "Access-Control-Allow-Origin: *", you should use "Access-Control-Allow-Origin:app.samedomain.com" to control which domains can access the API
To read more about CORS, check http://www.w3.org/wiki/CORS

Aside from that, it feels like an order of operations thing. All this should be before the callbacks.
type: 'GET',
url: _getBaseUrl() + endpoint,
data: null,
contentType: 'application/json',
dataType: 'json',

Related

Avoid CORS in rest API

I'm having a problem to make a call to a rest API.
In the document (FAQ) of the web application there is an example that use AJAX request to make the call. Here an example:
var url = 'https://example.com/yyy';
$.ajax({
type: 'POST',
url: url,
cache: false,
data: {
opt: JSON.stringify(example)
},
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function (result)
{
console.log(result);
} });
I created a local page with this code to made the post to the API that is located on a remote server but I receive an error about CORS.
Is there any solution to circumvent this problem? I tried to use firefox plugin to allow CORS but it didn't solve the problem. The session is authenticated via form before use the endpoint.
I see several issues:
Try to run the code from a domain and not from local disk (alternatively you can consider using https://crossorigin.me/ )
How does the authentication work? if with cookies you need to add withCredentials to the ajax request.
Make sure the API returns Access-Control-Allow-Origin: foo header where foo is the domain your code runs in. If you also used withCredentials, you should add Access-Control-Allow-Credentials: true

NTLM is automatically added instead of Bearer in AJAX Calls while calling API

In my website, something weird is happening while running in Internet Explorer. My website and API are hosted separately. API is having anonymous authentication with token based authorization. MVC website is having windows authentication. Most of the times everything works as expected. But sometimes what happens is while calling the API from javascript my Authorization is headed changed to NTLM instead of Bearer. I am giving some screenshots of the same scenario.
Successful API Call:
401 Unauthorized Call:
My Ajax is as follows:
$.ajax({
url: src,
type: 'GET',
cache: false,
async: true,
data: (parameters),
headers: {
'Authorization': 'Bearer ' + sessionStorage.getItem('token')
},
contentType: 'application/json'
dataType: 'json',
success: successCallback,
error: function (xhr, textStatus, errorThrown) {
ErrorPopup("error occur");
}
,
beforeSend: function (xhr, settings) { xhr.setRequestHeader('Authorization', 'Bearer ' + sessionStorage.getItem('token')); }
});
I have debugged all API calls and always authorization header is set to Bearer ... still, somehow some way NTLM is taking control of it and making my API calls unauthorized. Please share some insights how could I solve this. I cannot change authentication in IIS as it's beyond my control. If you need any more inputs I can provide that too.
It looks like there is a redundancy in your authorization headers (headers array + beforeSend). Remove one of them and test (reason : RFC 2616 says that several headers with the same name should be concatenated on the same line, and maybe the server is replying with an NTLM authorization request to such a request that it doesn't allow).

AWS API Gateway CORS Ajax Request Returning Error

I'm trying to use API Gateway as my server for a small database project, and I'm using Ajax to upload data to the server. I know I need to enable CORS to allow me to have cross-domain requests, and I've tried over and over multiple different methods of enabling CORS that I've found online, with no luck. No matter what I do, I seem to get the same error callback: {"readyState":0,"responseText":"","status":0,"statusText":"error"}
Here is the code I am using in the ajax request (for obvious reasons I omitted the URL of the API):
$.ajax({
type: 'POST',
url: API_URL,
data: data,
crossDomain: true,
dataType: "text",
contentType: 'text/plain',
success: (data, status, xhr) => {
alert("Success");
},
error: (e) => {
alert(JSON.stringify(e));
}
});
CORS is in fact enabled in my API, I can confirm this by checking the integration response for my OPTIONS method (there's only one resource and the only methods that exist for it are POST and OPTIONS). Any pointer in the right direction would be appreciated, trying to make this work has been very frustrating.

No 'Access-Control-Allow-Origin' when accessing gisgraphy api

Im trying to access gisgraphys api with this code:
$('[id$=PlaceOfDeparture]:not(.ui-autocomplete-input)').live('focus', function() {
$(this).autocomplete({
source: function (request, response) {
$.ajax({
type: 'POST',
datatype: 'jsonp',
url: 'http://services.gisgraphy.com/fulltext/fulltextsearch?q='+ request.term,
//data: {
// q: request.term
//},
success: function(res) {
console.log("Success: " + res);
},
error: function(res) {
console.log("Error: " + res);
}
});
}
});
});
when i do that i get error:
XMLHttpRequest cannot load http://services.gisgraphy.com/fulltext/fulltextsearch?q=viborgsslingan. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'mylocalhost' is therefore not allowed access.
if i press the link i get the xml in the browser just as i want it. Somehow it wont get to my code. Ive search a bit about the problem but it seems to be a security problem on the gisgraphy server... Is there anything i can do to make this cross-domain access work?
Ive search a bit about the problem but it seems to be a security problem on the gisgraphy server...
It’s not a security problem, rather the other way around. The Same Origin Policy forbids you from requesting data from other domains in JS via AJAX, unless the remote domain signals that it wants to explicitly grant you access (this is called CORS).
If the service you are accessing doesn’t offer that, and no other format that is not restricted by the SOP – like f.e. JSONP – then you can not get that data client-side via JavaScript.

Basic Authentication and jQuery/ajax call

I would like to call OData .NET web service that authenticates users via basic authentication.
I use following ajax call:
var fullUri = APIUri + "?$format=json";
$.ajax({
url: fullUri,
contentType: "application/json",
dataType: "jsonp",
type: 'GET',
jsonp: '$callback',
beforeSend: function setHeader(xhr) {
xhr.setRequestHeader('Authorization', token);
},
success: callback,
error: function (xhr, ajaxOptions, thrownError) {
alert(thrownError);
},
});
The results are unusable for me:
Calls are blocked because of CORS (until I will paste API url and try to load it in chrome). I tried local html file and html file uploaded to the same domain/port, but authentication fails (according to Chrome console).
Once I enter service URL into chrome address bar, I am asked to provide login name and password by Chrome. If I enter them, they are cached and used even I assign them in beforeSend. How to blocks this behavior?
I've tried a lot of examples how to configure jsonp, headers etc, but did not find working solution yet.
IIS server response header is also configured using "Access-Control-Allow-Origin" value="*".
You can set the HTTP Password and Username in the AJAX Call directly:
$.ajax({
url: fullUri,
contentType: "application/json",
username: <login>,
password: <password>,
...
Use the following to support CORS:
jQuery.support.cors = true;
Regarding the call, are you using HTTPS? Is the certificate valid?

Resources