'How to get CSRF token in iOS?

So I'm trying to POST form data to my colleague's site in order login (simple username and password) from my iPhone app. However, it appears that I need a CSRF Token in order to post. I've done a lot of research on this and from what I can obtain this token from the csrftoken cookie ( I read that here: https://docs.djangoproject.com/en/dev/ref/contrib/csrf/) using a GET request. The problem is, I don't know what exactly to do with this GET request? Where do I get from?

Here is the code so far for my post request:

NSURL *url = [NSURL URLWithString:SERVER_ADDRESS];
NSData* postData= //Some form data
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:@"POST"];
[request setValue:[NSString stringWithFormat:@"%d", postData.length] forHTTPHeaderField:@"Content-Length"];
[request setValue:@"application/x-www-form-urlencoded charset=utf-8" forHTTPHeaderField:@"Content-Type"];
[request setHTTPBody:postData];

[request addValue:token forHTTPHeaderField:@"X-CSRFToken"];  //Where do I get this token from

NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request
                                                              delegate:self];
[connection start];

I know there are a lot of similar posts to this on StackOverflow, but I haven't found any with an answer that seems complete. Usually it just directs me to the link above which is only filled with AJAX related info. Help would be much appreciated!



Solution 1:[1]

As pointed out in the comments you could either parse it from any page containing a form on your friend's website.

If you want one for your own ask him to render this template at /ios/

ios.html:

{% csrftoken %}

Then launch a GET request:2 You can parse the value of the token with a regex:

NSString *regex = @"csrfmiddlewaretoken\".*?\"\(.*?\)\"";

Finally you have to set the value of the X-CSRFToken on your following HTTP POST requests.

Solution 2:[2]

in order to login (POST) with the token, of course you have to get the CSRF token first, like you said. if you do a GET call to the login page first (before you follow up with a POST), the result of the login page will return a csrf_token which you can see if you use a browser (with open developer tools pane), and look at the network pane under response content to see the csrftoken cookie set by the server. in my case:

Set-Cookie:csrftoken=PgQEgY3LAynbVeWRIzXoo2VFRLfd8Uqt; expires=Fri, 10-Nov-2017 18:59:54 GMT; Max-Age=31449600; Path=/; secure

after parsing this out of the response, set a header like:

X-CSRFToken: "PgQEgY3LAynbVeWRIzXoo2VFRLfd8Uqt" 

in your POST with the login/password info. HTH

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Community
Solution 2 matias elgart