Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Forbidden (403) CSRF verification failed. Request aborted. Even using the {% csrf_token %}

i am trying to do a login in django but i get this error, i check the CSRF documentation and nothing works for me.

Here is the HTML:

<body>
  <section class="container">
    <div class="login">
      <h1>Login to Web App</h1>

      {% if form.errors %}
        <p class="error">Lo sentimos, la combinacion de usuario y contrasena no es correcta!</p>
      {% endif %}  

      <form action="/accounts/auth/" method="post">
      {% csrf_token %}  
      <input type='hidden' name='csrfmiddlewaretoken' value='randomchars'/>

        <p><input name="username" type="text" name="login" value="" placeholder="Username"></p>

        <p><input name="password" type="password" name="password" value="" placeholder="Password"></p>

        <p class="submit"><input type="submit" name="commit" value="Login"></p>
      </form>
    </div>
</body>

Like you see above i use the {% csrf_token %} and i have 'django.middleware.csrf.CsrfViewMiddleware' in my installed apps.

And my views are:

from django.http import HttpResponse,HttpResponseRedirect
from django.template.loader import get_template 
from django.template import Context
from datetime import datetime
from django.shortcuts import render_to_response
from django.http import HttpResponseRedirect
from django.contrib import auth
from django.core.context_processors import csrf

from models import *
from django.shortcuts import get_object_or_404
from forms import *
from django.template.context import RequestContext
from django.contrib.auth.decorators import login_required
from django.contrib.auth import authenticate, login

def login(request):
    c = {}
    c.update(csrf(request))
    return render_to_response('login.html', c)    


def auth_view(request):
    username = request.POST['username']
    password = request.POST['password']
    user = authenticate(username=username, password=password)
    if user is not None:
        auth.login(request.user)
        return HttpResponse('/accounts/loggedin') 
    else:
        return HttpResponse('/accounts/invalid')

i redirect to an other HTML file where i dont use the {% csrf_token %}.

like image 361
BismarthSantana Avatar asked Jan 03 '14 02:01

BismarthSantana


People also ask

How do I fix forbidden 403 CSRF verification failed aborted?

Are you trying to log in and are receiving a “Forbidden (403) CSRF verification failed.” message? What is happening is that our site's securities are in conflict with an autofill-enabled configuration in your browser. To fix, you can: Disable autofill, allow cookies, and clear your cache.

What does CSRF verification failed request aborted mean?

Forbidden (403) CSRF verification failed. Request aborted. You are seeing this message because this site requires a CSRF cookie when submitting forms. This cookie is required for security reasons, to ensure that your browser is not being hijacked by third parties.

What is Django Csrf_token?

csrf_token. Django has a {% csrf_token %} tag that is implemented to avoid malicious attacks. It generates a token on the server-side when rendering the page and makes sure to cross-check this token for any requests coming back in. If the incoming requests do not contain the token, they are not executed.


2 Answers

Theory


A couple of things are required to make the csrf protection work (check out the docs):

  1. Your browser has to accept cookies from your server
  2. Make sure you have 'django.middleware.csrf.CsrfViewMiddleware' included as middleware in your settings.py (alternatively use the decorator csrf_protect() on particular views you want to protect)
  3. Make sure you pass on the csrf token from django.core.context_processors.csrf to the context manager.

When you load your page, have a look in the page source using your favorite browser. Don't open the template html file, open the url which point to the view containing the form. Look at where you placed the {% csrf_token %}. If you see something like

<input type='hidden' name='csrfmiddlewaretoken' value="jdwjwjefjwdjqwølksqøwkop2j3ofje" />

you should be ok.

If you on the other hand see NOTPROVIDED, something has gone wrong while creating the csrf token. By looking in the source code (context_processors.py and csrf.py), we can find out what:

  • csrf(request) returns {'csrf_token': 'NOTPROVIDED'} if get_token(request) returns None.
  • get_token(request) returns request.META.get("CSRF_COOKIE", None).

I assume this means that it would return None if the cookie isn't successfully created.

Fix


For you, this means that you should first replace

<form action="/accounts/auth/" method="post" {% csrf_token %}>

with

<form action="/accounts/auth/" method="post">
{% csrf_token %}
(...)
</form>

We'd like the csrf field to be inside <form>...</form>, not inside <form>. As the code is at the moment, it will be converted to

<form action="/accounts/auth/" method="post" <input type='hidden' name='csrfmiddlewaretoken' value='randomchars' />>

and we would rather like

<form action="/accounts/auth/" method="post">
<input type='hidden' name='csrfmiddlewaretoken' value='randomchars' />

After that - have a look at the source code, and see if you can find the csrf field. If you can see it, everything should work in theory.

You can also check that the csrf cookie has been set in your browser, e.g. in Chrome, right-click the web page, and select Insepect Element. Select the Resources tab, and click on cookies. You should find a cookie name csrftoken there.

If you still have problems, double-check the middleware tuple in your settings.py and double-check that your browser accept cookier from your server as described above.

like image 120
Steinar Lima Avatar answered Oct 13 '22 01:10

Steinar Lima


Clear your browser cache and try again. Maybe it is using the CSRF token saved in cached cookie.

like image 31
Mohammad Etemaddar Avatar answered Oct 13 '22 00:10

Mohammad Etemaddar