Question

I use ajax calls against a thin tastypie layer to CRUD (using csrf tokens). Everything works like a charm until I run the site in e.g. Chrome incognito mode. I keep getting 401s on CUD requests.

Looking at the request cookies I find that the sessionid cookie is set but the csrftoken cookie is not (its properly set if I run in normal mode).

In my settings.py I have :

MIDDLEWARE_CLASSES = (
  'django.middleware.common.CommonMiddleware',
  'django.contrib.sessions.middleware.SessionMiddleware',
  'django.middleware.csrf.CsrfViewMiddleware',
  'django.contrib.auth.middleware.AuthenticationMiddleware',
  'django.contrib.messages.middleware.MessageMiddleware',
 )

Anyone ran into that issue and can save me some time here?

Thanks a lot, Juergen

Was it helpful?

Solution

I found the reason for the cookie not being set in Django's middleware file csrf.py. The code below if kicked in when in incognito mode preventing the cookie to be set:

    if not request.META.get("CSRF_COOKIE_USED", False):
        return response

My workaround is to set this value for my ModelResources in tastypie's api.py file manually:

class MyModelResource( ModelResource ) :

    [..]

    def wrap_view(self, view):
         def wrapper(request, *args, **kwargs):
             request.META["CSRF_COOKIE_USED"] = True
             wrapped_view = super(MyModelResource, self).wrap_view(view)
             return wrapped_view(request, *args, **kwargs)
         return wrapper
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top