On domain A (localhost:8080) I run this code to access an unauthenticating REST serivce on domain B (localhost):
req = new XMLHttpRequest();
req.open('GET', 'http://localhost/rest/service');
req.send();
This works fine and I do get my response across domains as I have Apache on domain B set the response header:
Header set Access-Control-Allow-Origin "http://localhost:8080"
However if I now turn on authentication for the REST service and try to run the same request:
req.open('GET', 'http://admin:admin#localhost/rest/service');
It now produces this error in Firebug:
Access to restricted URI denied" code: "1012
I'm confused that I am able to sucessfully make cross domain ajax calls to the authenticated service bypassing the same origin policy, yet when authentication is required on the service Firefox decides not to allow the ajax call? How can I fix this without using jsonp etc, as the production server won't be able to provide PHP or Servlet hosting.
It's easy with JQuery 1.5+, which I recommend you use for your JavaScript solution:
$.ajax({
url: 'http://admin:admin#localhost/rest/service',
crossDomain:true, // Here is the JSONP callback logic
success: function(data){
console.log(data); // data is what comes back from your remote file
}
});
Related
I'm trying to send POST Ajax request for third party service from my Outlook Add-in, but no matter what I tried I receiving Error: Access is denied, and status 0 (request never hit the server).
Assuming we are running IE9 or 8 behind the outlook I tried old school hacks like https://github.com/MoonScript/jQuery-ajaxTransport-XDomainRequest.
$.ajax({
url: endpoint,
data: JSON.stringify({'1':'2'}),
// headers: {'X-Requested-With': 'XMLHttpRequest'},
contentType: 'text/plain',
type: 'POST',
dataType: 'json',
error: function(xhr, status, error) {
// error
}
}).done(function(data) {
// done
});
Is there is something more I need to implement? Of cause I add my domain to manifest AppDomain property.
Cheers
The following needs to be done to send request to 3rd party service ...
Add the service URI to AppDomain list (you've done it.)
The service MUST have SSL endpoint; "https://your.domain" must be included within of "AppDomain" entry (see above)
The service has to allow CORS requests for your application (hosted Outlook App URI) domain or any domain. This is up to the service creators to allow or disallow client apps connections via Ajax.
As of observation of your code I notices you are sending JSON object, but setting content type to "text/plain". Contact the service creators to get information on what type of the data they accept as request. Usually services allow "application/json", but not plain text.
I am testing the jquery ajax calls to the API server from a different domain. Unfortunately I am getting an OPTIONS error. Here is my request code:
$.ajax({
url: "https://localhost:44356/api/Default/",
headers: {
"Authorization": "Bearer " + user.access_token
},
success: function (res) {
logAjaxResult(res);
},
error: function() {
logAjaxResult('Error');
}
}))
Which gives
XMLHttpRequest cannot load https://localhost:44356/api/Default/. Response for preflight has invalid HTTP status code 405.
Normally this is an easy fix - I install Microsoft.AspNet.WebApi.Cors, set up a provider and allow OPTIONS through always. I can see how I would normally do this on the Identity Server box too as there is a CorsProvider you can register up. My issue however is on the API box I am using IdentityServerBearerTokenAuthenticationOptions and I see no CORs options. When I try to set up the WebAPI.cors provider though I get an error saying there are multiple origins set on the server to allow. This indicates to me (correct me if I'm wrong) that the WebApi box has somehow got the CORs settings from my identity server box that is registered as it's authority. Is this right?
How do I configure to allow pre-flight requests with app.UseIdentityServerBearerTokenAuthentication(options)?
Many thanks
This issue was resolved when I found the documentation uses
Microsoft.Owin.Cors
I was using the package
Microsoft.AspNet.WebApi.Cors
We are trying to implement Github oAuth in our app using Passport.js. If the user hits the endpoint by clicking an anchor tag/href, it works fine, but if we use a click handler to initiate an ajax request instead, we receive a CORS error from the Github server. Why?
Server side code:
app.get('/auth/github',
passport.authenticate('github', { scope: [ 'user:email' ] }));
app.get('/auth/github/callback',
passport.authenticate('github', { failureRedirect: '/login' }),
function(req, res) {
console.log('Github authentication successful!');
res.redirect('/');
});
Client side code (we are using React):
--> Works:
<a href='/auth/github'>Contact</a>;
--> Does Not Work - CORS error:
handleContactAuth(event) {
$.ajax({
url: '/auth/github',
method: 'GET',
success: data => console.log( 'Contact Auth response: ', data),
error: err => console.log( 'Error connecting to GitHub.', err)
});
}
NOTE: This is a click handler on the React component and is functioning fine, as the ajax request is being triggered. I'm aware we're not handling the response currently, apart from just a console.log.
--> CORS Error we see on the Client side when using AJAX method instead of href:
XMLHttpRequest cannot load https://github.com/login/oauth/authorize? response_type=code&redirect_uri=ht…auth%2Fgithub%2Fcallback&scope=user%3Aemail&client_id=our_client_code. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access.
Any ideas? Would appreciate any insights - many thanks.
CORS error is not an error returned by the server, but one triggered by the browser if the response doesn't contain HTTP headers signaling that cross-origin requests are allowed. The endpoint you are hitting obviously isn't designed to be accessed like this.
I had the same problem and I found that at least in Google Chrome XMLHttpRequest object is restricted to same origin policy. So you may need to stick to using an anchor tag.
Regular web pages can use the XMLHttpRequest object to send and receive data from remote servers, but they're limited by the same origin policy. Extensions aren't so limited. An extension can talk to remote servers outside of its origin, as long as it first requests cross-origin permissions.
Link: https://developer.chrome.com/extensions/xhr
I'm using Ajax to download XML using HTTP GET getting following error:
XMLHttpRequest cannot load https://remoteserverfqdn:8444/cuic/permalink/PermalinkViewer.htmx?viewId=F52A08751000014B3835F5E80AB43E68&linkType=xmlType&viewType=Grid. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8080' is therefore not allowed access. The response had HTTP status code 403.
The code I'm using to get data:
$(document).ready(function()
{
$.ajax({
type: "GET",
url: "https://remoteserverfqdn:8444/cuic/permalink/PermalinkViewer.htmx?viewId=F52A08751000014B3835F5E80AB43E68&linkType=xmlType&viewType=Grid",
dataType: "xml",
success: parseXml
});
});
Remote server is a blackbox so there's nothing I can do on that side to enable Access-Control-Allow-Origin. I tried installing ARR and URL Rewrite on IIS to act as a reverse proxy. That works fine when accessing the page directly in a browser, but when using Ajax and HTTP GET it gives me the same error.
Does anyone know a different method I could use to download the xml bypassing CORS? I did read up on JSONP but I think a change on the server side (the blackbox one) is needed for that to work?
If ARR and URL rewrite is the correct way to go for this, does anyone know if there is a setting available there I'm missing to set the Origin HTTP header to the remote server url.
We are trying to create a RESTful API that will be hosted on server x.foo.com. Client html applications (built in jquery) will be hosted on y.foo.com.
I am dealing with cross-domain issues by setting the Access-Control-Allow-Origin header as described here http://www.w3.org/TR/cors/.
So far so good, and I can now successfully make AJAX calls from host y to host x.
However, I ran into a gotcha with POST requests. The typical response to a post request is a redirect. However, the XMLHttpRequest object will not follow cross domain redirects, thus resulting in a failed call.
// Hosted on y.foo.com
$.ajax({
type: "POST",
url : http://x.foo.com/myapp/",
success: function(data) {
alert("success!");
}
});
// Return status: 302
// (Which errors out in firebug)
Anyone know of any techniques to handle the redirect (to a resource on server x) that I get from this post for a client hosted on y?
How about the client sends a special header for AJAX requests, and depending on whether it's an AJAX request or not, you can change the response instead of doing a redirect.