我正在尝试使用基本身份验证调用https web服务(RESTful)。如果我将凭据放在url本身中,它会工作得很好,但我更愿意将它添加到请求中,这样密码就不会出现,例如在异常中。
我使用了以下代码:
NSURLCredential *credential = [NSURLCredential credentialWithUser:@"myuser"
password:@"mypassword"
persistence:NSURLCredentialPersistenceForSession];
NSURLProtectionSpace *protectionSpace = [[NSURLProtectionSpace alloc]
initWithHost:@"example.com"
port:443
protocol:@"https"
realm:nil
authenticationMethod:NSURLAuthenticationMethodHTTPBasic];
[[NSURLCredentialStorage sharedCredentialStorage] setDefaultCredential:credential
forProtectionSpace:protectionSpace];
NSURLConnection *theConnection = [NSURLConnection connectionWithRequest:theRequest delegate:self];但它不起作用。调用didReceiveAuthenticationChallenge委托方法,我可以在其中添加一个凭据,但理想情况下,我会将其与请求一起发送。
有什么想法吗?
发布于 2010-03-09 22:04:57
如果是基本身份验证,请尝试发送标头中的凭据。每次都对我有效。
用于发送请求标头中的用户名和密码
NSString *authString = [[NSString stringWithFormat:@"%@:%@", userName, password] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSString *finalAuth = base64 of authString;在请求中,添加一个标头,其中字段名为Authorization,值为"Basic " + finalAuth
发布于 2010-03-12 16:17:00
我错过了使用NSURLConnection的最后一行代码。确保您的代理正在响应以下内容:
- (BOOL)connection:(NSURLConnection *)connection canAuthenticateAgainstProtectionSpace:(NSURLProtectionSpace *)protectionSpace并为您的protectionSpace返回YES。
此外,请确保您的代理正在响应:
- (void)connection:(NSURLConnection *)connection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge在这里,您可以将创建的凭据分配给proposedCredential属性中的NSURLAuthenticationChallenge,以及将NSURLProtectionSpace实例分配到NSURLAuthenticationChallenge的protectionSpace属性中。
https://stackoverflow.com/questions/2326417
复制相似问题