如何在iOS中获得CSRF令牌? [英] How to get CSRF token in iOS?

查看:155
本文介绍了如何在iOS中获得CSRF令牌?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我试图将表单数据POST到我的同事的网站,以便从我的iPhone应用程序登录(简单的用户名和密码)。但是,看来我需要一个CSRF令牌才能发布。我已经做了大量的研究,从我可以从 csrftoken cookie 中获得这个标记(我读到这里: https://docs.djangoproject.com/en/dev/ref/contrib/csrf/ )使用GET请求。问题是,我不知道这个GET请求究竟是做什么的?我从哪里获取?

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];

我知道StackOverflow上有很多类似的帖子,但是我还没有找到任何有一个似乎完成的答案。通常它只是引导我到上面的链接只填充与AJAX相关的信息。帮助将不胜感激!

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!

推荐答案

为了登录(POST)与令牌,当然你必须得到CSRF令牌首先,就像你说的。如果您首先对登录页面进行GET调用(在跟踪POST之前),登录页面的结果将返回一个csrf_token,您可以使用浏览器(使用开放式开发人员工具窗格)查看,并查看在网络窗格的响应内容下查看服务器设置的csrftoken cookie。在我的情况下:

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

,设置一个标题,如:

X-CSRFToken: "PgQEgY3LAynbVeWRIzXoo2VFRLfd8Uqt" 



您的POST中的

登录/密码信息。 HTH

in your POST with the login/password info. HTH

这篇关于如何在iOS中获得CSRF令牌?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆