Django 1.2 CSRF and HTTP posts from Google Web Toolkit - django

I have a GWT web app working with Django server-side. I recently upgraded Django to 1.2, and am not able to get HTTP posts to work from my GWT app. I am getting this error:
CSRF verification failed. Request
aborted.
Reason given for failure:
CSRF token missing or incorrect.
I have enabled the csrf middlewares ('django.middleware.csrf.CsrfViewMiddleware', 'django.middleware.csrf.CsrfResponseMiddleware') which is working for contrib apps like login, but it seems as though the token is not getting added to posts made through GWT. Any ideas? Thanks in advance.

If you have checked the templates for auth.login you'll notice that a CSRF token is explicitly included inside the <form> tag.
<form method="post" action=".">
{% csrf_token %}
This is expanded into a hidden field when the page is rendered on a GET request. Something like:
<form method="post" action=".">
<div style='display:none'>
<input type='hidden' name='csrfmiddlewaretoken'
value='90064bf0e86edacfdb60595e3e2b8f23' />
</div>
This token is then passed back to the view on POST and validated.
Consequently before you can POST to a CSRF protected view you will have to first get the token from the said view.
Can you verify/ensure that you have the CSRF token handy before making a POST request to the view? Alternately you can disable CSRF protection for the view using the csrf_exempt decorator. This may not be a good idea though.
Update
This is the point of my question: I am not using django templates for my front-end and thus I cannot tag forms with the token. I am using GWT for my front-end, which is rendering the form for the post.
Are you already making a GET request to the Django view before rendering the page? In that case you can get the CSRF token by parsing the contents of the response.
If not you will have to explicitly make a GET request to the view (assuming it supports GET) and parse the response for a CSRF token. For an example see this question.

Related

csrf verification failed even after using csrf_exempt

Forbidden (403)
CSRF verification failed. Request aborted.
Help
Reason given for failure:
CSRF token missing or incorrect.
This error happens even after using csrf_exempt in the views.py page .How to resolve this issue?
https://i.stack.imgur.com/Y8tGL.png
Django handles csrf automatically so not need to exempt for your code just add csrf template tag in HTML Template like this...
<form action="" method="post">
{% csrf_token %}
</form>
and remove #csrf_exempt decorator which is on top of add_item
NOTE:- When you send POST request then require to add csrf token in html post form

CSRF verification failed. Request aborted. When I send POST request

I am sending a POST request to my server from an android application, but I am getting this error:
The POST looks like:
http://example/my_page_url/1000
Where the 1000 is an ID.
This is my views method:
def inventory(request, cross_id):
text_file = open("test.txt", "w")
text_file.write('POST Received')
text_file.write(cross_id.__str__())
text_file.close()
return render(request, 'Inventory.html', {})
my template code:
<form action='' method="POST">
<button type="submit" id="btn_save" name="btn_save">Save</button>
{% csrf_token %}
</form>
Actually, I don't really need to call a template, because I want to perform something on the server only. But I am calling the template just to prevent any errors for now.
I have read the other answers for the same problem but all of them have missed the CSRF token in the template or something else in the views method, but I believe the case is different here.
You need to add the X-CSRFToken header to all your POST requests.
You can get the appropriate value for this header from the cookie named csrftoken.
To test this in Postman, you need to enable the Interceptor plugin (top right corner).
Once you have it installed, make a GET request to /admin/login/ (make sure you are logged out from the site in the browser). In the cookies section you should see a cookie named csrftoken, copy its value.
Now, set the request type to POST for the same URL (/admin/login), add a header named X-CSRFToken with the value you copied earlier. Set the username and password fields in the Body section and hit send.
If your POST do not require authentication, you can use the csrftoken from an earlier GET request.

Handling errors when using custom forms with django-allauth

I'm using django-allauth and custom login and signup forms in my application. Everything works well until a user submits an error with the login or signup form.
The error shows up but on a different page.
e.g intended login form is at the URI: /payment/e886371a-fa52-4718-b8bc-e53fe8ac2bea/
However, when there is a form error in the above page, it redirects to the default login URI: /accounts/login/ and displays the error there.
Is there a way to make sure the user is returned to the original page incase of a form error and have the error(s) displayed there?
Thanks in advance.
If you have login form on URI /payment/e886371a-fa52-4718-b8bc-e53fe8ac2bea/ and you do not want to redirect to /account/login, do not write as action of form. And create payment view which can handle authorization directly on payment URI.
<form class="login" method="POST" action="/payment/e886371a-fa52-4718-b8bc-e53fe8ac2bea/">
...
</form>
In your payment view you can extends class allautho/accounts/views/LoginView, which handles normal email/password auth.

Mako csrf_token like in Django templates

I my recent Django-project I use mako templates.
About Cross Site Request Forgery CSRF.
In django templates there is the tag {% csrf_token %} to protect from hackers.
What about mako templates? Is there any analog of csrf_token or there is another protection mechanism???
Thanks!
I ran into the same problem just today (that's why I ended up here). I found a solution, at least, for what I wanted to do, which is pass some POST data to another view through an HTML form. Here it is:
From your first view, get a CSRF Token and add it to your (Mako) context:
from djangomako.shortcuts import render_to_response as render
from django.core.context_processors import csrf
def first_view(request):
"""This view generates a form whose action is 'second_view'."""
context = { "csrftoken": csrf(request)["csrf_token"] }
return render("path/to/yourtemplate.html", context)
yourtemplate.html's form must have a field named “csrfmiddlewaretoken” whose value is the CSRF Token, which we placed in the context as “csrftoken”. As in:
<input type="hidden" name="csrfmiddlewaretoken" value="${ csrftoken }" />
Source: Cross Site Request Forgery protection (Django 1.5 Docs)
There's some sample code at Django Snippets that looks to do this, although judging by the comments, you may need to fiddle a bit. If you have trouble, you basically want to make sure that you're duplicating the Django stock CSRF tag (click the link, start on line 87).

Django CSRF fails when used in an extended page

All pages are extended from a base template.
There is a form in the base template and the form has the CSRF tag. When submitting the form while on home page, all works fine. However for all other pages (also extended from same base template) the submit fails with the following error:
Forbidden (403)
CSRF verification failed. Request aborted.
Inspecting the page with Firebug, the hidden input field that holds the CSRF token is missing.
You need to do this -
In settings modify - MIDDLEWARE_CLASSES = ('django.middleware.csrf.CsrfViewMiddleware')
Next to any form in your templates, put this - <form method="post" class="login_form" name="frmlogin">{% csrf_token %}
This would solve your problem...