我正在尝试使用基本身份验证调用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
委托方法被调用,我可以在那里添加凭证,但理想情况下我会发送请求。
有什么想法吗?
答案 0 :(得分:2)
如果是基本身份验证,请尝试在标头中发送凭据。每次都适合我。
用于在请求标题中发送用户名和密码
NSString *authString = [[NSString stringWithFormat:@"%@:%@", userName, password] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSString *finalAuth = base64 of authString;
在您的请求中,添加一个包含字段名称授权和值"Basic " + finalAuth
答案 1 :(得分:0)
我错过了使用NSURLConnection的最后一行代码。确保您的代表回复:
- (BOOL)connection:(NSURLConnection *)connection canAuthenticateAgainstProtectionSpace:(NSURLProtectionSpace *)protectionSpace
并为您的protectionSpace返回YES。
另外,请确保您的代理人回复:
- (void)connection:(NSURLConnection *)connection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge
您可以在此处将您创建的凭据分配给proposedCredential属性中的NSURLAuthenticationChallenge
,并将NSURLProtectionSpace
实例分配到NSURLAuthenticationChallenge
的protectSpace属性中。