Chrome extension and XHR with permission - javascript

I'm working on a Chrome extension and I've some issue with a XHR cross-domain. Let me explain: I set right permission in manifest.json for a domain and I make (in my js file) a simple XMLHttpRequest. Request works fine but responseXML field is null. Why? It is not an issue with SOP and responseText correctly contains HTML text of the page requested. How I can parse it? I can't do it with DOMParser().parseFromStringeven with using https://developer.mozilla.org/en/DOMParser implementation, I receive everytime a single.
Some suggestions? My (simple) code is following:
var req = new XMLHttpRequest();
req.open("GET", "http://somedomain.com", true);
req.overrideMimeType("text/xml");
req.setRequestHeader("Content-Type", "text/xml");
req.onload = anonymousFunction;
req.send(null);
Thanks for any replies!

Related

Access-Control-Allow-Origin: Access for all users just to one site

I'm currently coding a php website which reads certain values from a json file from my server.
Now when i request the xmlhttp request to my server, i get the Access-control-allow-origin ERROR in console. I already find out i have to set Access-control-allow-origin: *; in my Apache configuration but i don't want to use * because I don't want to give everyone access to my website. So how can i just give permission for one json file to every client?
var requestURL = 'https://myWebsite/blabla.json';
var request = new XMLHttpRequest();
request.open('GET', requestURL);
request.responseType = 'json';
request.send();
request.onload = function() {
var response = request.response;
jackpot = response.items[0].value;
var inner = document.getElementById("myid");
inner.innerHTML = jackpot+" EURO";
this is my js code and i always get the Error, except i use Access-control-allow-origin: *, which i dont want to use because its unsave.
Please care im little new to web coding so im not really professional sorry.
In your PHP backend, allow only to your domain for Access-control-allow-origin not *. So that it will be safe.

"ActionController::InvalidCrossOriginRequest" error with AJAX request by plain JavaScript

I have code like:
jQuery.ajax({
url: url // Some URL
});
The above code worked perfectly. But, I have a requirement to convert this code to pure JS. So, I did:
var xhttp = new XMLHttpRequest();
xhttp.open("GET", url, true);
xhttp.send();
But, here when the AJAX request is fired I get this error in rails server log:
ActionController::InvalidCrossOriginRequest - Security warning: an
embedded tag on another site requested protected JavaScript.
If you know what you're doing, go ahead and disable forgery protection
on this action to permit cross-origin JavaScript embedding.
NOTE: I had faced similar error when I passed format: :js in link_to(Fix I referred). But, this happens with pure JavaScript code.
How do I fix this?
Adding xhttp.setRequestHeader("X-Requested-With", "XMLHttpRequest"); fixed the cross origin error in rails.
Now, the code looks like:
var xhttp = new XMLHttpRequest();
xhttp.open("GET", url, true);
xhttp.setRequestHeader("X-Requested-With", "XMLHttpRequest");
xhttp.send();

Converting cURL to JQuery.ajax request

Hi I'm working on connecting to an API that is using Layer 7 as an IP authorizer and eGalaxy as a credentials authorizer, when the curl request is sent a line of xml is sent back to me. I'm currently working on localhost, I've implemented the Access-Control-Allow-Origin chrome extension.
My curl request looks as such:
curl https://client-url/eGalaxy.aspx -H 'Content-Type:text/html' --data '<?xml version:"1.0" encoding="UTF-8"?><Envelope><Header><SourceID>0</SourceID><MessageID>131</MessageID><MessageType>Authenticate</MessageType></Header><Body><Authenticate><Username>*username*</Username><Password>*password*</Password><PasswordEncrypted>NO</PasswordEncrypted></Authenticate></Body></Envelope>' --insecure
When I tried to create an ajax request I receive an "Invalid HTTP status code 500" error and "OPTIONS url" which drops down to show:
n.ajaxTransport.k.cors.a.crossDomain.send # jquery-2.1.3.js:4
n.extend.ajax # jquery-2.1.3.js:4
(anonymous function) # VM947:2
InjectedScript._evaluateOn # VM899:895
InjectedScript._evaluateAndWrap # VM899:828
InjectedScript.evaluate # VM899:694
My ajax code is as follows:
$.ajax({
url:'https://client-url/eGalaxy.aspx',
data:'<?xml version:"1.0" encoding="UTF-8"?><Envelope><Header>
<SourceID>0</SourceID><MessageID>131</MessageID>
<MessageType>Authenticate</MessageType></Header><Body>
<Authenticate><Username>*username*</Username>
<Password>*password*</Password>
<PasswordEncrypted>NO</PasswordEncrypted></Authenticate></Body>
</Envelope>',
type:'POST',
contentType:'text/xml',
dataType:'xml',
success: function(data){
},
error: function(){
}
});
Any help with translating into a proper AJAX request would be appreciated!
EDIT: If this makes a difference these are the headers that are returned with the client's xml when the curl is complete(client information deleted)
This application will be made into a widget as well, so it will not be running off of a hosting site.
UPDATE 1: I'm using #KevinB's suggestion that the CORS headers were still not properly added.
Here is my updated JS code, copied from this link:
var url = 'https://client-url/eGalaxy.aspx';
var data = '<?xml version="1.0" encoding="UTF-8"?><Envelope><Header><SourceID>1</SourceID><MessageID>131</MessageID><MessageType>Authenticate</MessageType></Header><Body><Authenticate><Username>*username*</Username><Password>*password</Password><PasswordEncrypted>NO</PasswordEncrypted></Authenticate></Body></Envelope>';
var xhr = createCORSRequest('POST', url);
xhr.send(data);
function createCORSRequest(method, url) {
var xhr = new XMLHttpRequest();
if ("withCredentials" in xhr) {
// Check if the XMLHttpRequest object has a "withCredentials" property.
// "withCredentials" only exists on XMLHTTPRequest2 objects.
xhr.open(method, url, true);
} else if (typeof XDomainRequest != "undefined") {
// Otherwise, check if XDomainRequest.
// XDomainRequest only exists in IE, and is IE's way of making CORS requests.
xhr = new XDomainRequest();
xhr.open(method, url);
} else {
// Otherwise, CORS is not supported by the browser.
xhr = null;
}
return xhr;
}
var xhr = createCORSRequest('GET', url);
if (!xhr) {
throw new Error('CORS not supported');
}
When run with the CORS Chrome extension off I receive an Access-Control-Allow-Origin =! 'null' error. Knowing that CORS needs Access-Control-Allow-Origin header to =! 'null' will this cause problems in the future with making this into a widget that will be put into a Content Manager system?
With it on the origin is set to 'www.evil.com', with the only error in the code being that it says the xhr.send() is an anonymous method. Using breakpoints I can see the xhr in xhr.send() is set to an empty request:
> XMLHttpRequest {response: "", responseText: ""}
Inside the createCORSRequest this line is undefined. I've tested using 'GET' and 'POST' as the method.
xhr.open(method, url, true)
EDIT 2:
Using #Fabiano's approach I've changed the web.config for two versions of what I suspect is my server(?). I'm attaching screenshots of what I've gone through
No luck, so far. Decided to use xhr.AppendHeader:
I decided to use xhr.setRequestHeader("Access-Control-Allow-Origin", "*");
The Network tab Headers for eGalaxy.aspx
There is an error in your XML. You put version:"1.0", and this makes the XML invalid.
Change to version="1.0" and try to make your request. It should work.
This may be the cause for the "Bad request" error.
You can validate your XML here: enter link description here
EDIT: After some research, the problem may be with the headers sent by your server. Your server (or page, .aspx in this case) seems to skip the header you need, the "Access-Control-Allow-Origin: *".
Look at this link: http://enable-cors.org/server.html
This site shows you how to implement it for your server. Since the page you are requesting is called eGalaxy.aspx, then you have 2 ways to implement the headers:
1- Put the line Response.AppendHeader("Access-Control-Allow-Origin", "*"); if the page is a simple ASP.NET application. If it uses Web API 2, you need to implement a different way as it is shown here: http://enable-cors.org/server_aspnet.html
2- Edit the web.config file on the root of your server and add these lines inside the tag:
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="*" />
</customHeaders>
</httpProtocol>
For a ASP.NET application, these are the ways you have. The link I mentioned has solutions for other applications, take a look and choose the right one. :)
Note that the value * tells you that your server will accept any cross-origin request. This may lead to a security issue, so the best you can do is to put your domain address instead of *.
I hope it helps!

Cross Domain XHR failing inspite of Access-Control-Allow-Origin header

I am new to XHR and am trying to solve a simple use case. I have a web server, from where my javascript would fetch data. But instead of serving the data itself, the server would redirect the javascript XHR request to an alternate location (for example a file on Amazon's S3) to fulfill the request.
This brought me into the world of cross domain XHR, and I am unable to get even a simple example working inspite of reading a bit about it. I am adding "Access-Control-Allow-Origin: *" to the header in my main domain which serves the web page containing the javascript. But it does not work. What am I missing? I need this to work regardless of browser so am looking for something the initial server can do other than serving as a proxy, which defeats the purpose of offloading the request to S3.
Chrome : Gives "Exception: NetworkError: DOM Exception 19" on the
second call.
IE: Shows a warning but opens second url after
confirmation.
Firefox: Just says "Exception: Faliure" on the second
call.
Code follows for test.php:
<?php
header('Content-type: text/html');
header('Access-Control-Allow-Origin: *');
?>
<!DOCTYPE html>
<html>
<header>
<script type="text/javascript">
var request;
var url1 = "data/file.csv";
var url2 = "http://stackoverflow.com/users/1293955/ng-algo";
try
{
if (window.XMLHttpRequest) {
// IE7+, Firefox, Chrome, Opera, Safari
request = new XMLHttpRequest();
}
else {
// code for IE6, IE5
request = new ActiveXObject('Microsoft.XMLHTTP');
}
// load data. 'false' indicates that further script
// is not executed until data is loaded and parsed
alert("Test1 with url: "+url1);
request.open('GET', url1, false);
request.send();
alert(request.responseText);
alert("Test2 with url: "+url2);
request.open('GET', url2, false);
request.send();
alert(request.responseText);
} catch (e) { alert("Exception: "+e.message); }
</script>
</header>
This is a test page
</html>
For any arbitrary request (given the mix of Amazon and Stack Overflow in the question), CORS may not be enough as it's actually the remote server that has to give the permission.
For the 2nd request to succeed, stackoverflow.com would have to include relevant Access-Control-Allow-* headers in their responses that give your website permission to make the request. And whether those are included in the response or not is entirely up to Stack Exchange, in this case.
Also, by including Access-Control-Allow-Origin: * in the response, you're actually allowing other websites to request your page from their origin.
What you may need is a "proxy" script on your server. You can find a generalized solution from Ben Alman:
http://benalman.com/projects/php-simple-proxy/
https://github.com/cowboy/php-simple-proxy
Which would allow:
request.open('GET', 'proxy.php?url=' + encodeURIComponent(url2), false);

JavaScript client for Spring WS

I have spring soap web service that works well. But my js client
var req = new XMLHttpRequest();
if(req.readyState == 4){....}
req.open('POST', 'http://localhost:8080/CurrencyService', true);
req.setRequestHeader("Content-Type", "text/xml");
req.send(msg);
throws
405 Method Not Allowed - http://localhost:8080/CurrencyService
How can I fix it?
I don't know anything about Spring WS, but apaprently whatever you have defined to handle /CurrencyService doesn't accept a POST. Skimming the docs I'd say your WebServiceMessageReceiverHttpHandler is missing or misconfigured.

Categories