Simple CORS does not work (even though it should) - javascript

I'm trying to hack my back-end, which exposes a REST API. The worst thing that can happen to my database according to firefox CORS policy is that I can create a new object with POST request, as it does not need a preflight. This is the simple code (I'm running it via jsfiddle, but it shouldn't mean a thing)
var xhttp = new XMLHttpRequest();
xhttp.open("POST", "http://127.0.0.1:8000/api/v1/company", true);
xhttp.withCredentials = true;
xhttp.setRequestHeader('Content-Type', 'text/plain');
xhttp.send('{description:"This company was added by pure hacking"}');
But I'm getting an error in the console:
Blocked loading mixed active content "http://127.0.0.1:8000/api/v1/company"

The error is not because of SOP, its a mixed content error, that is making an http request on a https page.
jsfiddle defaults to https but allows http, but only on saved fiddles.
Change the url of your fiddle to use http instead of https

Related

Access-Control-Allow-Origin in http request

I am running a server on my localhost with an HTML5 application.
I would like to send an http-request to a second server "130.100.100.100:50000".
I have the following JavaScript code running on localhost where I am sending http requests to the second server.
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {}
};
xmlhttp.open("GET", "http://130.100.100.100:50000/company.html/query?a0=" + a0, true);
xmlhttp.setRequestHeader( 'Access-Control-Allow-Origin', '*');
xmlhttp.send();
The second server is receiving my queries but I don't get any answer for my request. I think the problem is that the Same Origin Policy is violated. I tried to use the CORS standard to set
Access-Control-Allow-Origin: *
But the GET requests I am sending still doesn't contain "Access-Control-Allow-Origin" in the header. If I send the request manually with "Access-Control-Allow-Origin: *" everything is working proper. Do I have a mistake in my JavaScript code? I would like to avoid using jQuery.
You need to allow cross origin on server. Follow https://ma.ttias.be/set-access-control-allow-origin-cors-headers-apache-vhost-htaccess/
You need a page used as a proxy. This page will send a GET request to the target page and display the response. Make sure that relative paths at img, a, script and link are converted to full paths. If you do this, the CORS problem will be fixed.

Api Gateway cannot allow Access-Control-Allow-Origin

This url is in AWS API Gateway with method get and stage is well deployed.
And I enabled CORS following the aws document.
Here are my steps to enable CORS.
-Resource->action->enable CORS->
default setting ->enable CORS and replacing the CORS headers.
There is no error log in CORS result.
I am not a profesional web developer and my browser is safari.
Here is my code to query "http://my.com"
function request(idex) {
var xmlHttp = new XMLHttpRequest();
xmlHttp.onreadystatechange = function() {
if (xmlHttp.status == 200)
callback(xmlHttp.responseText);
}
xmlHttp.open("GET", "http://my.com", true);
xmlHttp.send(null);}
The console print the error :
XMLHttpRequest cannot load "http://my.com" Origin http://example.com is not allowed by Access-Control-Allow-Origin.
If there are some mistakes in javascript request or in API Gateway deploy?
After consulting and trying each method, I found the error as following.
According to AWS document, we can not deploy our api before enabling CORS. All the settings about the header and CORS must be set before being deployed.
But the API Gateway does not block this setting nor does it show any error dialog. API Gateway will not change the header even if your setting process shows success.
The cross origin problem is from server side not javascript side. When the server does not allow request from other domains it throws cross origin error. But you said you already added CORS in aws instance
As the javascript is only accessing the service from my.com, You need to added proper domain mapping in your my.com site to tell that request will come from another domain called example.com. might be the server is not properly configured. or try if server is expecting any header.
try to see the result in any rest client like soapui, rect client plugin in chrome, etc. once you confirm that there is no problem in server, try it from javascript
To test there is a chrome plugin you can try
https://chrome.google.com/webstore/detail/allow-control-allow-origi/nlfbmbojpeacfghkpbjhddihlkkiljbi?hl=en

JavaScript XMLHttpRequest vs curl

using curl I can send a POST request to
"http://myusername:mypassword#SomeURL" to trigger an action
Using xml http request I've tried doing the same thing but running the following code:
xhttp = new XMLHttpRequest();
xhttp.open("POST", "http://myusername:mypassword#SomeURL", true);
xhttp.setRequestHeader("Content-Type", "text/plain");
xhttp.send();
Greets me with the error:
POST http://myusername:mypassword#SomeURL 403 (Forbidden)
Now why would this be ? Is accessing an url like this via a browser, curl, arc... etc different from accessing it via .js ?
Furthermore I've tried posting to said url using the action of a form and it worked swimmingly, but I'd prefer to get things done in JavaScript if possible for this specific task.
So... ahm, any ideas ? The documentation behind the XMLHttpRequest that i've seen has been rather lack-luster for a technology that "carries the modern web upon its shoulders".
Necessary reading to solve this question:
Basic Authentication With XMLHTTPRequest
How can you encode a string to Base64 in JavaScript?
I am deliberately not adding a code sample; the linked questions have everything you need.
Sounds like you might need to enable CORS (cross-origin resource sharing)

Remote calls via javascript

I run a service where there is a javascript file that is called and self executed on a user's site.
This then calls an external server every 10 or so seconds with a bunch of variables.
I used to do this by using a createElement('script') and then setting the path to a file on the external server and passing the required variables across by means of GET variables. (works well for small URI's)
This worked really well and seemed to work cross browser as well with no undesired effects.
The problem I then ran into was when I needed to extend the amount or size of the variables that were being sent across. So obviously I decided to change from GET method to POST, but by doing that I could no longer use the createElement('script') trick and had to opt for the XMLHttpRequest() (ala Ajax - without jQuery) method which worked really well, except for the minor problem of having to also cater for Internet Explorer and Opera which didn't really play ball too well (big shock). So I used the following:
function createCORSRequest(method, url){
var xhr = new XMLHttpRequest();
if ("withCredentials" in xhr){
xhr.open(method, url, true);
} else if (typeof XDomainRequest != "undefined"){
xhr = new XDomainRequest();
xhr.open(method, url);
} else {
xhr = null;
}
return xhr;
}
var request = createCORSRequest("post", "http://xx.xxxx.com/");
if (request){
request.onload = function(){
//do something with request.responseText
};
request.send(myPostObjectDataVariableGoeshere);
}
..which I found over at this page
This is basically just a fallback to using the XDomainRequest() method which InternetExplorer wants you to use instead..
Fantastic, BUT -> Looking in the Console of Developer Tools in IE it says:
SEC7118: XMLHttpRequest for http://xx.xxxx.com/ required Cross Origin Resource Sharing (CORS).
SEC7120: Origin null not found in Access-Control-Allow-Origin header.
SCRIPT7002: XMLHttpRequest: Network Error 0x80070005, Access is denied.
But what's really odd about this is that I've already got the following as the first line in my backend PHP file that is being called (which works for other browsers...)
header('Access-Control-Allow-Origin: *');
Someone please tell me what's wrong here.. Also if there is a better way to be doing this instead of fighting the browser wars..
Note: I cannot use jQuery for this task!
You should try jQuery for this task. Its much easier and don't have that problem with IE.
http://api.jquery.com/jQuery.ajax/
IE unfortunately block Cross Origin requests, i believe there is no simple way to get around it by script only, but you can try tuning the options or via my proxy script.
Tuning the options
Internet Explorer ignores Access-Control-Allow headers and by default prohibits cross-origin access for Internet Zone. To enable CORS go to Tools->Internet Options->Security tab, click on “Custom Level” button. Find the Miscellaneous -> Access data sources across domains setting and select “Enable” option.
Proxy Script on local server as a Bridge
Previous post:
Remote POST request with jQuery and Ajax
This is for you to place a PHP script on a local server and do a local AJAX request and proxy to the remote server for good.

Error: "Access to restricted URI denied"

Access to restricted URI denied" code: "1012 [Break On This Error]
xhttp.send(null);
function getXML(xml_file) {
if (window.XMLHttpRequest) {
var xhttp = new XMLHttpRequest(); // Cretes a instantce of XMLHttpRequest object
}
else {
var xhttp = new ActiveXObject("Microsoft.XMLHTTP"); // for IE 5/6
}
xhttp.open("GET",xml_file,false);
xhttp.send(null);
var xmlDoc = xhttp.responseXML;
return (xmlDoc);
}
I'm trying to get data from a XML file using JavaScript. Im using Firebug to test and debug on Firefox.
The above error is what I'm getting. It works in other places i used the same before, why is acting weird here?
Can someone help me why it's occuring?
Update:
http://jquery-howto.blogspot.com/2008/12/access-to-restricted-uri-denied-code.html
I found this link explaining the cause of the problem. But I didn't get what the solution given means can someone elaborate?
Another possible cause of this is when you are working with a .html file directly on the file system. For example, if you're accessing it using this url in your browser: C:/Users/Someguy/Desktop/MyProject/index.html
If that then has to make an ajax request, the ajax request will fail because ajax requests to the filesystem are restricted. To fix this, setup a webserver that points localhost to C:/Users/Someguy/Desktop/MyProject and access it from http://localhost/index.html
Sounds like you are breaking the same origin policy.
Sub domains, different ports, different protocols are considered different domains.
Try adding Access-Control-Allow-Origin:* header to the server side script that feeds you the XML. If you don't do it in PHP (where you can use header()) and try to read a raw XML file, you probably have to set the header in a .htaccess file by adding Header set Access-Control-Allow-Origin "*". In addition you might need to add Access-Control-Allow-Headers:*.
Also I'd recommend to replace the * in production mode to disallow everybody from reading your data and instead add your own url there.
Without code impossible to say, but you could be running foul of the cross-site ajax limitation: you cannot make ajax requests to other domains.

Categories