CSRF in django rest_framework

I am very much into connecting different front-ends (angularjs, javascript, titanium appcelerator, and so on…) to a rest back-end as you may have seen on previous articles. This made me aware of problems with django’s CSRF protection, yet another developer hiccup

What is CSRF?

CSRF, standing for cross-site request forgery is a kind of attack in which a malicious web site cheats a user to perform actions on some other web site where the user may be authenticated (some evil purposes included). This is achieved by placing forms or links to the site where the user is logged in. Most systems nowadays are including protection against this kind of attack by ensuring that the form that performs the action is only present in your site. This is achieved by setting a server side known token into the form (as an alternative for a referral based system that could be spoofed).

For those interested in a more detailed explanation check csrf protection on the security tips for web developers

Well as for now, as django rest_framework with session based authentication includes csrf and since I haven’t manage to get the csrf_exempt decorator in my rest_framework class based views, I have added this token to the login/signup response of my auth api

On my client, now a mobile application written with titanium appcelerator, upon login I store the token inside a global var (sic)

Then pass it into next non-safe rest calls inside a header called X-CSRFToken

Et voilĂ !

 

Bytefilia