我需要:
1)针对表单身份验证服务进行身份验证
2) 保存 cookie
3) 使用 cookie 调用 web 服务
我正在努力让它发挥作用。有没有人有这方面的运气?这似乎是一个非常常见的操作。
这是我的代码:
点击 auth URL 并获取 cookie:
- (IBAction)buttonGetCookieTap:(id)sender {
[[NSHTTPCookieStorage sharedHTTPCookieStorage] setCookieAcceptPolicy:NSHTTPCookieAcceptPolicyAlways];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:self.cookieURL];
[request setHTTPShouldHandleCookies:YES];
[request setHTTPMethod:@"POST"];
self.urlConnection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
}
- ( void )connection: (NSURLConnection *)connection didReceiveResponse: (NSURLResponse *)response
{
NSHTTPURLResponse *HTTPResponse = (NSHTTPURLResponse *)response;
NSDictionary *fields = [HTTPResponse allHeaderFields];
self.cookie = [fields valueForKey:@"Set-Cookie"];
}
- (void)connection:(NSURLConnection *)connection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge
{
NSURLCredential *credential = [NSURLCredential credentialWithUser:@"blah"
password:@"blah"
persistence:NSURLCredentialPersistenceForSession];
[[challenge sender] useCredential:credential forAuthenticationChallenge:challenge];
}
现在使用 cookie 调用 auth 服务:
- (IBAction)buttonCallServiceTap:(id)sender {
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:self.dataURL];
[request addValue:self.cookie forHTTPHeaderField:@"Cookie"];
self.urlConnection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
}
编辑:对不起,我遇到的问题是我只用会话 id 得到了一个准系统 cookie,但在服务器端,cookie 看起来很好。谁能验证我的 cookie 抓取代码没有问题?我已经尝试了很多变体并且遇到了同样的问题。谢谢!