request.format is null on XMLHttpRequest() to rails server - ruby

I have a rails app that is responding to requests at the url '/copy/:collection/:email'. From the app, I'm sending the request with an XMLHttpRequest() as:
var req = new XMLHttpRequest();
req.onreadystatechange = function(){
console.log(req);
}
req.open("GET", '/copy/' + collection + "/" + copyTo, true);
req.send();
The server receives the request and performs the correct action, but on completion returns a Completed 404 Not Acceptable in ...
I notice in the log that where it might normally say Processing by XController#copy as JS, the log only reads: Processing by XController#copy as. I've put in some debug and determined that request.format is nil. Is there a way to set this when sending my request?

Simplest way would be to add an extension to the URL like so
req.open("GET", '/copy/' + collection + "/" + copyTo + ".js", true);
Another way would be set the Accept header for the http request to text/javascript. I believe this would be done like so (not tried it myself)
req.setRequestHeader("Accept", "text/javascript")
req.open("GET", '/copy/' + collection + "/" + copyTo, true);

Related

The HTTP request must contain a user-specific secret - Error in fortify

I have below code in my applicaton.
makeAjaxRequest: function(url, data){
var xhr = new XMLHttpRequest();
xhr.open('POST', url, true);
xhr.onload = function () {
var response = Ext.JSON.decode(xhr.responseText);
if (response) {
Ext.Msg.alert('Alert', response.message);
Ext.getBody().unmask();
}
};
Ext.getBody().mask('Loading...');
xhr.send(data);
}
Fortify is showing this error for this line
Error - "The http request at * line * must contain a user-specific secret in order to prevent an attacker from making unauthorized requests"
xhr.open('POST', url, true);
How do i resolve this fortify issue?
Is it something Fortify is highlighting because it doesn't have full context of the application.
In my application i have SSO setup which is passing a user specific secret with every request. But fortify may not be aware of it and ends up flagging this as an issue.
Kindly advice on what is best way to resolve this issue.
Thanks.
You need to add the setRequestHeader !!!
xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
xhr.send(data);

Google RECAPTCHA always returning error missing-input-response in the response

Google RECAPTCHA always returning error missing-input-response in the response when I try to check the correctness. How does the call to the service go, to the URL https://www.google.com/recaptcha/api/siteverify ?
The format is:
https://…/api/siteverify?secret=[…]&response=[…]&remote_ip=[…]
Make sure that Content-Type is set to application/x-www-form-urlencoded
.Net example
using (HttpClient httpClient = new HttpClient())
{
var response = await httpClient.PostAsync(GoogleVerificationUrl + "?secret=" + ReCaptchaSecretKey + "&response=" + ReCaptchaResponse, new StringContent("", Encoding.UTF8, "application/x-www-form-urlencoded"));
}

Flask error after redirect from POST method

I am using a combination of Flask and Javascript. After user input from a web page I send a JSON object back to the Flask server. ie:
var xhr = new XMLHttpRequest();
xhr.open('POST', '/completed/');
xhr.setRequestHeader('Content-Type', 'application/json');
var stringifiedObject = dataResultToJSON(data);
xhr.send(stringifiedObject);
Then in Flask:
#main_view.route('/completed/', methods=['POST'])
def completed():
if (request.headers['Content-Type'].startswith('application/json')):
#do stuff here
return redirect(url_for("main_view.home"))
#main_view.route('/')
def home():
logger.debug(">>home")
return render_template('home.html')
When flask redirects to 'home' asfter the Ajax POST I get the following console output:
DEBUG:myapp:>>home
INFO:werkzeug:127.0.0.1 - - [24/Apr/2016 20:13:15] "GET / HTTP/1.1" 200 -
INFO:werkzeug:127.0.0.1 - - [24/Apr/2016 20:13:15] "GET /%3C!DOCTYPE%20html%3E%3C!-- (... entire web page html)
The odd thing is the second INFO statement above - I don't get this line printed when I redirect to home from anywhere else - only occurs when I redirect from the 'completed' POST method. Werkzeug logs the entire home.html web page html and I get an error in the web client:
NetworkError: 404 NOT FOUND - http://127.0.0.1:5000/%3C!DOCTYPE%20html%3E%3C!-- (... entire web page html)
I also added code=307 to the redirect as per here: Make a POST request while redirecting in flask but still got the same 404 error.
I am stuck as to how to get around this.
I think your problem is that you're POSTing data as an AJAX request (i.e. not a browser navigation, but programatically from your client). It doesn't really make much sense to tell your AJAX client to redirect after the POST completes.
You're then trying to tell the client to redirect...but the redirect request is being returned to the XMLHttpRequest.
I'm not 100% sure what you want to happen, but you'd probably be better off using a regular form post if you want the client to redirect once you've posted the data.
I believe what you're trying to do is better illustrated by the answer to this question:
How to manage a redirect request after a jQuery Ajax call
I got this working following the comment and answer above. Specifically I did:
def completed():
#other code here
return url_for("main_view.home")
and in JS:
xhr.onreadystatechange = function() {
if (xhr.readyState == XMLHttpRequest.DONE) {
var OK = 200;
if (xhr.status === OK) {
window.location.href = xhr.responseText;
}
else {
console.log ('Error: ' + xhr.status);
}
}
};

Chrome extension - redirecting an https AJAX request to the same url in onBeforeRequest

I am redirecting every request to the same url in onBeforeRequest listener using redirectUrl directive. It works fine with all sites as Chrome eventually send the request to the url. But I am loosing an AJAX request for one site (the request is not sent at all, e.g. https://apiv2.abc.com/me?token=fiYoEdDLZxPJ...). If I replace return {redirectUrl: request.url}; with just return, everything is fine. Can I redirect every request to itself as the following? I tried this with and without requestHeaders permission. Your suggestions are needed please.
chrome.webRequest.onBeforeRequest.addListener(
function interceptRequest(request) {
if (request.tabId === -1) return;
console.log("In before request: " + request.requestId + ", URL: " + request.url);
return {redirectUrl: request.url};
}, {urls: ['*://*/*']}, ['blocking']);

ajax from Chrome-Extension processed, but receive responseText="" and status=0

I am writing a google-chrome extension, that needs to make ajax requests to a server, send some data, and receive some data back. My server is Tomcat 6.0, running on localhost.
I am able to receive all the data on the server side, do all the processing I need, and send a response back to the extension,
but the status i get in the callback is 0, and responseText="".
my guess is that the problem lies either in the server - returning a response to a request originating from chrome-extension://... url, or in the extension - receiving a response from localhost:8080.
I've set the necessary permissions of course, and I tried setting content-type of the response to "text/xml", "text/html" and "text/plain" - it makes no difference.
I've tried using ajax both with XMLHttpRequest and JQuery - same problem with both.
I've found these issues, but they don't seem to solve my problem:
1. http://www.plee.me/blog/2009/08/ajax-with-chrome-empty-responsetext/
2. http://bugs.jquery.com/ticket/7653
here's my code:
bg.js (background page)
function saveText(data) {
var requrl = serverUrl + addTextUrl;
var params = json2urlParams(data);
jQuery.ajax({
type : "POST",
url : requrl,
data : params,
success : function (data, textStatus, XMLHttpRequest) {
console.log("Data Saved: " + msg);
}
});
// var xhr = new XMLHttpRequest();
// xhr.open("POST", requrl, true);
// xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded");
// xhr.onreadystatechange = function (progress) {
// if (xhr.readyState == 4) {
// console.log("Data Saved: " + this.response);
// }
// };
// xhr.send(params);
}
addContentServlet.java: (server side)
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
ErrorCodes error = addContent(request, response);
response.setContentType("text/plain");
//response.setContentType("application/x-www-form-urlencoded; charset=UTF-8");
//response.setIntHeader("errorCode", error.ordinal());
response.getWriter().write(error.toString());
response.setIntHeader("errorcode", error.ordinal());
if(error == ErrorCodes.SUCCESS){
response.setStatus(error.toHttpErrorCode());
response.flushBuffer();
}
else{
response.sendError(error.toHttpErrorCode(), error.toString());
}
}
EDIT:
I've noticed in the chrome console of the background page that for every ajax that returns to the extension i get a
XMLHttpRequest cannot load
http:// localhost:8080/stp_poc/MyServlet.
Origin
chrome-extension://fmmolofppekcdickmdcjflhkbmpdomba
is not allowed by
Access-Control-Allow-Origin.
I tried loosing bg.js and puting all the code in the main page instead - to no avail.
how come XMLHttpRequest agrees to send the request, but not receive it back??
Maybe a server-configuration problem? I'm a newb, so maybe i missed something basic, like a header in the response
EDIT
I've finally pinned the problem:
I shouldn't have included the port number in my permission. Here's the wrong permission I wrote:
"permissions" : [
"http://localhost:8080/"
]
And here's the correct form:
"permissions" : [
"http://localhost/"
]
everything seems to works fine now.
The problem was that I shouldn't have included the port number in my permission.
Here's the wrong permission I wrote:
"permissions" : [
"http://localhost:8080/"
]
And here's the correct form:
"permissions" : [
"http://localhost/"
]

Resources