我有一个 iOS 应用程序需要登录到一个使用 Django 的现有网站,并需要 CSRF 令牌才能登录。我无法更改这一点。
我的当前尝试是向服务器发送 GET 请求,该请求将返回 CSRF,然后将该 cookie 作为字符串抓取并附加到 POST 请求中。
NSMutableURLRequest *req = [[NSMutableURLRequest alloc] initWithURL:[[NSURL alloc] initWithString:@"http://example.com"]];
[req setHTTPShouldHandleCookies:YES];
[NSURLConnection sendAsynchronousRequest:req queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
self.csrf_cookie = [[(NSHTTPURLResponse *)response allHeaderFields] valueForKey:@"Set-Cookie"];
[self postLoginCredentialsEmail:@"user@example.com" password:@"password"];
}];
- (void)postLoginCredentialsEmail:(NSString *)email password:(NSString *)password {
NSMutableURLRequest *req = [[NSMutableURLRequest alloc] initWithURL:[[NSURL alloc] initWithString:@"http://example.com/login"]];
[req addValue:(self.csrf_cookie != nil ? self.csrf_cookie : @"poo") forHTTPHeaderField:@"X-CSRFToken"];
[req setHTTPMethod:@"POST"];
NSString *postData = [NSString stringWithFormat:@"password=%@&;email=%@", password, email];
[req setValue:@"application/x-www-form-urlencoded; charset=utf-8" forHTTPHeaderField:@"Content-type"];
[req setHTTPBody:[postData dataUsingEncoding:NSUTF8StringEncoding]];
[NSURLConnection sendAsynchronousRequest:req queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
NSLog(@"response from login: %@", response);
}];
}
我已获取了cookie,但仍然出现“CSRF令牌不正确或缺失”的错误。
我看过其他帖子,这些代码大多来自那里,但仍然失败。
我已比较服务器在我的请求和网站上的良好请求中收到的内容,唯一的区别似乎是良好请求具有HTTP头字段
HTTP_X_CSRFTOKEN
,其中只有CSRF令牌,而我的请求具有格式'HTTP_X_CSRFTOKEN': 'csrftoken=tokenkey; expires=expirydate; Max-Age=age; Path=/, mws-track-id=somestuff; httponly; Path=/ '
。