Without Django + AJAX templates: is the JSRT CSRF token updated during a browsing session?

My current setup is AngularJS + Django 1.5, and I completely abandoned the use of the Django template engine (i.e. the backend is pretty much an API server).

Since I do not use the template tag csrf_token, Django, in turn, does not set or send a cookie csrftokenin response. As stated in the official docs, the decorator ensure_csrf_cookie()should be used to make the decorated look send a cookie csrftoken.

I applied a decorator ensure_csrf_cookie()to a view that serves the first GET request that my web client calls upon boot. At the same time, my web client receives a CSRF trick and is now allowed to call unsafe methods (like POST) to the server.

The above setting works fine only if the CSRF token remains the same until the browsing session ends.

Question: Does the Jango CSRF token mean during a browsing session? If yes, does this mean that I will need to apply the decorator ensure_csrf_cookie()to all the representations that I have?

+4
source share
2 answers

1) Is the Jango CSRF token updated during the browsing session?

It seems that the CSRF token is unique for each session, but it is based on my observations, I do not have an “official” source. Using Angular.js, I use the following code without problems:

angular.module('app', ...)
  .config(function($httpProvider) {
    var cookies = document.cookie.split(';');
    var csrftoken = _.find(cookies, function(v) { 
                      return v.trim().indexOf('csrftoken=') == 0; 
                    });
    if(csrftoken) {
      $httpProvider.defaults.headers.common['X-CSRFToken'] = csrftoken.split('=')[1];
    }
  })

HTML Django, Angular bootstraps cookie .

2) "", , _csrf_cookie() , ?

CSRF. django-cors-headers , API- REST.

() ensure_csrf_cookie():

  • - APIView
  • CSRFCookie .
  • ensure_csrf_cookie()
+5

@Paulo Scardine ensure_csrf_cookie() ( ), , ensure_csrf_cookie() . middleware , ensure_csrf_cookie. - :

app.middleware.py:

from django.middleware.csrf import get_token


class EnsureCsrfCookie(object):

    def process_request(self, request):
        # Forces process_response to send the cookie
        get_token(request)

settings MIDDLEWARE_CLASSES:

MIDDLEWARE_CLASSES = (
    .,
    .,
    .,
    'app.middleware.EnsureCsrfCookie',
    .,
    .,
    .,
)

, . , - .

0

All Articles