[Answer]-Handling CSRF tokens in Django

1👍

I got it working and this is how I did it. Like suggested by toto_tico I worte a dummy view that I retrieve thought GET to get the CSRF token. At first it didn’t send the csrf token over GET so I had to add the decorator ensure_csrf_cookie.

@ensure_csrf_cookie
def dummy(request):
    return HttpResponse("done")

And then I handle login requests normally.

def my_login(request):
    ...handle login...

It turned out that just adding the cookie to the POST wasn’t enough, I had to write a token to the POST data as well.

def _helper(self, url, method="POST"):
    req = urllib2.Request(host + url)
    self.cookieMgr.add_cookie_header(req)
    try:
        if method == "GET":
            response = self.opener.open(req)
        else:
            for cookie in self.cookieMgr:
                if cookie.name == "csrftoken":
                    csrf = cookie.value
            values = { "csrfmiddlewaretoken" : csrf}
            params = urllib.urlencode(values)
            response = self.opener.open(req, params)
            code = response.getcode()
            info = response.info()
            content = response.read()
            return code, info, content
    except urllib2.HTTPError as ex:
        print str(ex)
        sys.exit(1)

def get_csrf(self):
    url = "/license/dummy"
    self._helper(url, method="GET")

def login(self, username, password):
    self.get_csrf()
    url = "/license/login?username=%s&password=%s" % (username, password)
    code, info, content = self._helper(url)
    if code == 200:
        #done!
👤dutt

0👍

You have to add the csrftoken cookie value when you make a request to Django. Alternatively you can add @csrf_exempt to your Django backend to accept those requests.

0👍

Start reading about CSFR and ajax. I usually do the following with the code provided:

  1. Create a csfr.js file
  2. Paste the code in the csfr.js file
  3. Reference the code in the template that needs it|

If you are using templates and have something like base.html where you extend from, then you can just reference the script from there and you don’t have to worry any more in there rest of your programming. As far as I know, this shouldn’t represent any security issue.

Leave a comment