JQuery + AJAX + Django = CSRF ? [duplicate] - javascript

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
"CSRF token missing or incorrect" while post parameter via AJAX in Django
I wanted to send login data by AJAX to authenticate user, but it wasn't possible because of CSRF. Could You tell me what to add to my code to make it woking?
my JavaScript file:
$("#login").live("click", function() {
var username = $(".login_username").val();
var password = $(".login_password").val();
$.ajax({
url: "/login",
type: "POST",
data: {
username: username,
password: password
},
cache: false,
success: function(tekst) {
alert(tekst);
}
});
});

There is a method explained here.
It consists of adding a X-CSRFToken header on each ajax request.
This is done by hooking in the jQuery.ajaxSend event, so everything is done automatically (you just have to copy and past their code, and run it once before the first ajax request you make).

I've been trying to solve the same problem, And as arnaud576875 says you have to Add the csrf token header on each ajax request just like the Django docs says https://docs.djangoproject.com/en/dev/ref/contrib/csrf/#ajax And execute that code before any Ajax request you make.
But there is something additional, you have to find a way to load the csrf token to the cookies of your app before trying to do any AJAX request, after a lot of painful hours researching I couldn't find an specific answer of how to do this, what I did found is that to ensure that your view sends the csrf token within a cookie you can use the ensure_csrf_token() to each view you want to receive the token https://docs.djangoproject.com/en/dev/ref/contrib/csrf/#django.views.decorators.csrf.ensure_csrf_cookie this seems to work for a lot of people, but did not worked for me.
Another way is using the Legacy Method, adding the 'django.middleware.csrf.CsrfResponseMiddleware' to your MIDDLEWARE_CLASSES but I don't recommend this method because leaves several security risks.
https://docs.djangoproject.com/en/1.2/ref/contrib/csrf/#legacy-method
All this methods that I said before did not worked for me. The way that I'm allowing Ajax to do some requests is as the following, and if someone finds this a dangerous method please let me know:
Go to the first view that your user will hit, like the /home/ page.
Insert this before redirecting or parsing anything
request.META["CSRF_COOKIE_USED"] = True
And that's it, That is the way that works for me, but as I said before I'm not sure if this is the right method or the most secure one to accomplish the csrf protection.

Related

Post request come from which page

I have a simple post request that comes from one specific page of my site:
reqdata = 'text=' + mytext;
$.ajax({
type: "POST",
url: "/request.php",
data: reqdata,
cache: false,
success: function(html) {
alert(html)
}
});
It goes to another page of the same site .. So the first page calls page mydomain.com/test.php calls http request to mydomain.com/request.php
How do I recognise on page mydomain.com/request.php that the original page the request come from was mydomain.com/test.php?
I wish to ensure that the request can be done only from this exact page mydomain.com/test.php and not from other domains nor page.
I do the request using ajax and javascript and therefore I think that I cannot add a hidden authentication that would ensure the whole thing is secure. Because each value is seen on the original page source code.
It seems you are searching for a way to protect yourself against Cross Site Request Forgery (XSRF).
The common way to protect against XSRF is to render some time limited key on your page (just some <script> var mySecret = <?php (someSecret) ?>) and keep track of these. You could use the first characters of the session id for example and check if the request data contains this field. You can just add this to your data with something like ...&secret=mySecret When there is a session id with the first characters of this data attribute, you accept the request, otherwise you reject it on your server (possibly with error code 403).
So this question would be
best practices to avoid XSRF on my site
and should be asked on the information security stack exchange.

MediaWiki: How do I use an AJAX POST in JS to send data to a custom API extension (PHP)?

I've been stumped on this for a while. I've successfully created a MediaWiki API extension from which I'm able to extract data using an API url, but now I want to go the other way. I want to use JS to send a simple bit of data to the server for storage in a session variable (in PHP). I've experimented with something like the following:
$.ajax({
// start POST request
type: "POST",
// url to which the request is sent
url: "/",
// data to the server
data: { myvariable: 0 },
// Type of data
dataType: 'json',
// Funciton to be called if the request succeeds
success: function( data ){
console.log("POST successful with " + data);
}
})
What I don't fundamentally get is how to "pick up" the POSTed data in PHP. In my research, I came upon something saying I should look for $_POST['myvariable'] in PHP. Yet I'm not sure how or where I'd create something that would listen for such a POST from JS. It seems to me the easiest solution to this would be if I could write a method onto my API extension that simply assigns the value of the myvariable that's POSTed to the session variable whenever that thing is POSTed. I've written this method already, in fact, but it's unclear to me how I'd instruct AJAX to invoke it in PHP. I've also read that this type of thing may not be advisable for security reasons.
I've seen advice elsewhere suggesting I should do something in JS like:
var api = new mw.Api();
...and then use the Api object's methods to execute Ajax GET and POST requests. Well, I tried creating an instance of this object, and it throws errors on the console that say it's not a recognized function or something of that nature.
I'm rather new at all this, but I'm at my wit's end trying to figure out something that in theory ought to be very simple. Any suggestions?

Submit PHP form without reloading or AJAX

I know this question must've been asked various times here but I have not found a solution from all links I could search for. I don't understand how to do this.
I have a form, with 2 textboxes and 1 submit button. The form name is 'form1'
here is what I was using till now:
<script type="text/javascript">
$("#form1").submit(function() {
$.ajax({
type: 'GET',
url: 'response.php',
data: {1: $("#txt1").val(), 2: $("#txt2").val()},
success: function (data) {
$("#update").prepend(data);
},
error: function (xhr, ajaxOptions, thrownError) {
alert(thrownError);
}
});
});
</script>
'update' is a table.
I am adding a new row to it after the data is parsed in response.php.
Now, the problem is, using AJAX for this is not at all secure. Users can use plugins such as 'Tamper Data' for firefox to mess with these and send any data they want regardless of what they entered. Thus, making me vulnerable to XSS and CSRF attacks.
So I tried a different approach, I set the form's action to response.php.
Now, there are 2 problems in doing that:
The page refreshes.
How can I make the table row prepend via PHP that too in another document? Earlier I was just echoing it and then AJAX prepended the data for me.
To make things clear: There is no other way than "refreshing" or AJAX.
You should stick to AJAX. To amend your security concerns, you can add a token to the form, which is only valid for this user (saved in his session on login). Therefore noone else can send data in his name and thus eliminiating the risk for XSS and CSRF.
You need to transmit that token in your AJAX request and check it in response.php.
Validation in response.php:
Escape everything which goes into your database. mysql_real_escape_string or PDO will help you with that.
When you output userdata somewhere in your page use htmlspecialchars().
You might also consider strip_tags() before saving or printing any values.
Since you're submitting a form request, you should be using POST instead.
Secondly, ajax post is no less secure than a regular post so you should not be worried.
Third, if you're worrying about someone sniffing your network. Have your website use HTTPs instead.
To prevent XSS attacks, you should be modifying your data before printing it to the end user using something like htmlentities.
To prevent sql injections, I would suggest using PDO or atleast escape your userinput before.
Removing AJAX isn't the solution to solve XSRF and XSS vulnerabilities. Instead you should use form tokens, two step forms, etc to prevent this.
Using session tokens isn't very hard - you just have to generate a token for each form, save them on the server and compare the send token with them on the server. To be really secure, you should generate a token for each form, but you could also use a token for each session.
Btw. XSS isn't a problem of ajax or some form posts - it's a problem of not escaping malificious output. htmlentities and stuff like this, should help you.

jQuery ajax load html from another server [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Load website into DIV
Hey all i am trying to find a way to call an external website and retreve its HTML so that i can check for something in it (wither the user entered a valid VIN # or not depending on what this website calls back)
This is the code i have:
$.ajaxSetup ({
cache: false
});
$("#load_callback").click(function(){
$.ajax({
url: 'http://www.google.com',
dataType: 'text',
success: function(data) {
alert(data);
}
});
});
It works but only if i have it pointed to my server (and running on my server also). Is there a way i can call an external website using jquery/ajax? I am aware of the Same origin policy but was hoping something like what i want to do did not fall into that catagory?
I cant even get an iFrames title? Really??? wow....
David
You need to use jsonp: http://en.wikipedia.org/wiki/JSON#JSONP
These links should explain it:
http://www.remysharp.com/2007/10/08/what-is-jsonp
http://www.ibm.com/developerworks/library/wa-aj-jsonp1-
The other option you have is to write your own server-side proxy to it, i.e. have a page/controller/handler on your server that passes your request through and returns the result. It won't be as fast as going direct, and it will increase your site's traffic, but it will get you around the security problem.
Stick to simple things, if you want to load websites, be simple and go with iframe. If you want to make request use PHP or similar. For example you can use curl method to make request to another websites through PHP. Or even simpler, setup a form to request to another web server.

Get jQuery post redirect response

I've written some HTML/Javascript that sits on a third-party server for security reasons. This page performs a javascript post to another page on the same site. However, instead of responding with useful data, it instead wants to perform a redirect (if you would post via a normal HTML form to this page, it would redirect your browser). How can I process this process? I basically want to be able to extract the url's query parameters that it is trying to redirect with (and then put this link into a hidden form field).
Here is my basic ajax post...
$.ajax({
url: '/someurl/idontcontrol',
data: serialized_form_data,
async: false,
type: 'POST',
success: function(data, textStatus, x) {
alert(x);
alert(x.getAllResponseHeaders());
return false;
$('#redirect_link').val(WHAT_DO_I_PUT_HERE);
}
});
Note that the URL I am posting to is not one that I control, so I have no power over what it returns.
UPDATE: When I use the above alerts, I receive "[object XMLHttpRequest]" and "null". I'm monitoring the headers with a Firefox plugin and they seem be coming back as expected, but I can't seem to access them via javascript (I've also tried x.getResponseHeader('Location'), but that and all other calls to getResponseHeader return empty).
ALSO: I don't know if it matters, but the status code is 302 (as opposed to 301 or 303).
Thanks!
According to the jQuery Documentation the success method can take a third argument which is the XMLHttpRequest object.
According to Mozilla's XMLHttpRequest page, this object should have a "status" property. If you check the value of this property, and it is a redirect code, such as 301 (permanent redirect) or 303 (temporary redirect) it is known the processing page is trying to perform a redirect. The "statusText" property should be able to be used to determine the location it is trying to redirect you to.
If you know it is trying to redirect, you can then re-post the data through Ajax to the new URL.
The strange thing is though, when researching this, stumbled across this page that indicates the XMLHttpRequest object should follow redirects (see the comments). So it seems like this would be a non-issue.
Unless the processing page is using an HTML meta redirect (like below) to do the redirection. In that case, I'm not sure what could be done - maybe try to parse the returned HTML for meta tags and see if any of them are attempting a redirect.
<meta http-equiv="refresh" content="0;url=http://www.example.com/some-redirected-page">
You can't get the full HTTP headers from an AJAX call in JQUery, so you can't process the redirect in this way.
However with a raw javascript request you do have access to the XMLHttpRequest getAllResponseHeaders() method which will allow you to process the redirect (this function for single headers).
Sorry, not directly an answer to your question, but I'm sure it's possible with jQuery too as it's quite simple with Prototype.
// Warning: this is Prototype, not jQuery ;-)
//...
onComplete: function(response) {
var refresh = response.getResponseHeader("Refresh");
var whatever = response.getResponseHeader("Whatever");
}
//...

Categories