web 服务可以在返回 http 响应时附带认证要求 challenge,作用是询问 http 请求的发起方是谁,这时发起方应提供正确的用户名和密码(即认证信息),然后 web 服务才会返回真正的 http 响应。
- (
void
)connection:(
NSURLConnection
*)connection didReceiveAuthenticationChallenge:(
NSURLAuthenticationChallenge
*)challenge
{
// 之前已经失败过
if ([challenge previousFailureCount ] > 0 ) {
// 为什么失败
NSError *failure = [challenge error ];
NSLog ( @"Can't authenticate:%@" , [failure localizedDescription ]);
// 放弃
[[challenge sender ] cancelAuthenticationChallenge :challenge];
return ;
}
// 创建 NSURLCredential 对象
NSURLCredential *newCred = [ NSURLCredential credentialWithUser:@"sid"
password:@"MomIsCool"
persistence:NSURLCredentialPersistenceNone];
// 为 challenge 的发送方提供 credential
[[challenge sender] useCredential:newCred
forAuthenticationChallenge:challenge];
收到认证要求时,
NSURLConnection 的委托对象会收到相应的消息并得到一个
NSURLAuthenticationChallenge 实例。该实例的发送方遵守 NSURLAuthenticationChallengeSender 协议。为了继续收到真实的数据,需要向该发送方向发回一个
NSURLCredential 实例。代码示例如下:
方法来自:NSURLConnectionDelegate
{
// 之前已经失败过
if ([challenge previousFailureCount ] > 0 ) {
// 为什么失败
NSError *failure = [challenge error ];
NSLog ( @"Can't authenticate:%@" , [failure localizedDescription ]);
// 放弃
[[challenge sender ] cancelAuthenticationChallenge :challenge];
return ;
}
// 创建 NSURLCredential 对象
NSURLCredential *newCred = [ NSURLCredential credentialWithUser:@"sid"
password:@"MomIsCool"
persistence:NSURLCredentialPersistenceNone];
// 为 challenge 的发送方提供 credential
[[challenge sender] useCredential:newCred
forAuthenticationChallenge:challenge];
}
如果是更复杂,安全要求更高的 web 服务,可能会要求请求的发送方提供一张或多张证书以确认身份。不过多数 web 服务只需要提供用户名和密码。
程序可以保留 credential, 并有以下三种保留模式。
- NSURLCredentialPersistenceNone :要求 URL 载入系统 “在用完相应的认证信息后立刻丢弃”。
- NSURLCredentialPersistenceForSession :要求 URL 载入系统 “在应用终止时,丢弃相应的 credential ”。
- NSURLCredentialPersistencePermanent :要求 URL 载入系统 "将相应的认证信息存入钥匙串(keychain),以便其他应用也能使用。