Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

django admin login suddenly demanding csrf token

Tags:

django

I was logging into my django admin console easily a few minutes ago. I must have changed something somewhere that caused this error when logging in as superuser:

Forbidden (403) CSRF verification failed. Request aborted.

This error caught me off guard as I was logging in all night. Why would I suddenly need a csrf token for admin login? You would think the sign in form already has that. This is my admin.py:

from django.contrib import admin from accounts.models import Image, Category, UserProfile  class ImageAdmin(admin.ModelAdmin):     list_display    = ["__unicode__", "title", "created"]  admin.site.register(Image, GenericImageAdmin)  class CategoryAdmin(admin.ModelAdmin):     list_display    = ["category"]  admin.site.register(Category, CategoryAdmin)  admin.site.register(UserProfile) 
like image 569
codyc4321 Avatar asked Apr 11 '15 01:04

codyc4321


People also ask

How do I ignore CSRF token in Django?

1. Using @csrf_exempt decorator. The is will import the @csrf_exempt decorator that allows you to easily disable CSRF validation for specific views. Just place @csrf_exempt decorator immediately above the view for which you do not want CSRF protection.

How does Django generate CSRF token?

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. Django makes this process seamless with the addition of a simple tag to the form generated.

What is CSRF and how does Django protect against this attack?

CSRF protection works by checking for a secret in each POST request. This ensures that a malicious user cannot “replay” a form POST to your website and have another logged in user unwittingly submit that form. The malicious user would have to know the secret, which is user specific (using a cookie).


1 Answers

Admin login normally does require a csrf token, but that's normally all taken care for you.

  1. Check your browser's cookies to see if there is a csrf token present
  2. Try clearing cookies and refreshing
  3. Check to make sure you have django.middleware.csrf.CsrfViewMiddleware in your middleware
  4. Check that you're either on https or you have CSRF_COOKIE_SECURE=False (which is the default) in settings, otherwise your csrf cookie exists but won't be sent. Purge your cookies after changing CSRF_COOKIE_SECURE.
like image 128
ubadub Avatar answered Sep 23 '22 22:09

ubadub