How to get CSRF token in iOS?

So, I'm trying to send POST data to my colleague’s website to log in (simple username and password) from my iPhone application. However, it looks like I need a CSRF token to publish. I have done a lot of research on this and from the fact that I can get this token from the csrftoken cookie (I read that here: https://docs.djangoproject.com/en/dev/ref/contrib/csrf/ ) using GET request. The problem is that I don’t know what exactly to do with this GET request? Where do i get

Here is the code for my mail 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 that there are many similar posts in StackOverflow, but I have not found an answer that seems complete. Usually it just directs me to a link above which only information related to AJAX is populated. Help would be greatly appreciated!

+8
django ios iphone
source share
2 answers

As stated in the comments, you can either analyze it on any page containing a form on your friend’s website.

If you want one of you to ask him to make this template in /ios/

ios.html:

 {% csrftoken %} 

Then run the GET request: 2 You can parse the value of the token using a regular expression:

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

Finally, you must set the X-CSRFToken for the following HTTP POST requests.

0
source share

to enter (POST) with the token, of course, you must first get the CSRF token, as you said. if you first call GET on the login page (before you follow the POST), the result of the login page will be returned csrf_token, which you can see if you use a browser (with the developer toolbar open) and look at the network panel according to response content to view 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 answer, set the header, for example:

 X-CSRFToken: "PgQEgY3LAynbVeWRIzXoo2VFRLfd8Uqt" 

in your POST with login / password information. Hth

0
source share

All Articles