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

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']);

Related

Can Ajax make a Cross-Origin Login?

I'm trying to login from one of my servers to another in order to send cross-origin requests that requires being logged. is it possible?
I have two web servers, A and B. Lets say www.a.com and www.b.com.
B has an API that can be used only if the client is logged in. I need to use that API from A clients.
So, I send from A client an ajax (post) login request to B. B responses with CORS headers, the session cookie and a successful redirection to B's home/index.
But when I make a second ajax request (jsonp request) from A client to B server, this request doesn't send the previous session cookie received, therefore the login request failed.
If I login to www.b.com manually (in a second browser tab), all requests from A to B are successful detected as a logged user, so, the B API works from A.
I think that the session cookie received from my login requests is not being saved to the browser.
This is my login request:
$.post("www.b.com/login", { 'j_username': 'username', 'j_password': 'password' } );
Using:
jqXHR.withCredentials = true;
settings.crossDomain = true;
Response headers:
Access-Control-Allow-Headers:x-requested-with
Access-Control-Allow-Methods:POST, GET, OPTIONS
Access-Control-Allow-Origin:*
...
Location:http://www.b.com/home
...
Set-Cookie:JSESSIONID=tY++VWlMSxTTUkjvyaRelZ0o; Path=/
The cookie received is being saved to www.a.com or to www.b.com? How can I set this cookie to www.b.com from an A client ajax request? I think that is the problem.
As apsillers said, we can't use the wildcard Access-Control-Allow-Origin:*.
But this doesn't solved the problem.
I was setting jqXHR.withCredentials = true; inside a beforeSend handler function.
$.post({
...
beforeSend: function(xhr) {
xhr.withCredentials = true;
},
...
});
And for some reason, this doesn't work. I had to set the use of credentials directly:
$.post({
...
xhrFields: {
withCredentials: true
},
...
});
This code works perfectly !
Thanks you.

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);
}
}
};

ajax json request , always returning error

Hello i've got a problem with ajax json request. Im always getting an error, even if the requests are succeeded. At the moment i have this code:
function sumbitLoginForm(user, pass) {
if (user.trim() == '' || pass.trim() == '') {
alert("You must enter username and password!");
} else {
$.ajax({
type : 'POST',
url : 'https://url.php',
dataType : 'json',
data : {
userlogin : user,
userpass : pass
},
contentType: "application/json;",
success : function(data) {
$("#images").html("uspeshno");
},
error : function(data) {
$("#images").html("greshka");
}
});
}
return false;
}
$(document).ready(function() {
clearPageInputs();
$("#submitButton").click(function() {
sumbitLoginForm($("#username").val(), $("#password").val());
});
});
Im always getting an error , no matter what username and password i type . But the status of request is changing , if i type correct user and pass i get status 302 Moved temporarly , but when i type wrong user or pass i get status 200 OK . What am i doing wrong ?
PRG Pattern and Ajax
It looks like your server returns a HTTP 200 status code when the userid and password will not validate. This is proper behavior, as HTTP error codes not meant for application errors, but for HTTP protocol errors.
When the userid and password are matched succesfully, you are redirected to another page. This is also normal behavior, e.g. to prevent other people to re-use your login credentials using the back key.
This is called the Post/Redirect/Get pattern.
See: http://en.wikipedia.org/wiki/Post/Redirect/Get
The problem is that the PRG pattern does not play nice with Ajax applications. The redirect should be handled by the browser. It is therefore transparent for the jQuery code. The Ajax html response will be the page that is mentioned in the Location header of the 302. Your Ajax application will not be able to see that it is being redirected. So your are stuck.
In one of my projects I solved this on the server side. If I detected an Ajax call, I would not send a redirect but a normal 200 response. This only works if you have access to the server code.
If you cannot change the redirect for your Ajax calls, then you can parse the response headers or the html to see if you were being redirected and act accordingly. Probably the login will set a cookie, so you might try and look for the presence of that cookie.

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

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);

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