[Answer]-Adding csrf_token to my post request from iPhone app

1👍

The Django CSRF Middleware uses cookies and forms and whatnot to send a code to the page, then make sure the correct page is the one sending information back. In both cases, you must do a GET request to the server, and if you have the middleware installed correctly, it will put the CSRF token into a cookie for you.

Check out the documentation for more info on this.

Now, I noticed you’re using a library that uses NSURLConnection, so that should handle cookies for you. I got this bundle of code (untested) that lets you pull the cookie name that you specify in your settings file (again, check out the documentation link above) then put that in your POST.

NSArray *cookies = [[NSHTTPCookieStorage sharedHTTPCookieStorage] cookiesForURL: networkServerAddress];
for (NSHTTPCookie *cookie in cookies) 
{
    // get the right cookie
}

Of course, if you’re only making POSTs and never GETs first, you don’t have a CSRF token to send!

And that’s why we have the @csrf_exempt tag. (Docs here) This is the way to go 99% of the time, since most apps you won’t do a GET before you do a POST. (in webpages you have to do a GET first). Note that this is intended only when an app is sending only POSTs and there’s no session to speak of. You really need to think about your own security when using this, and how you verify that a given app/user really is who they claim to be. And how you disable people from hitting this URL from a webbrowser.

TLDR: Probably use @csrf_exempt on the view, but be careful.

Leave a comment