NSURLCredential

 

NSURLCredential 身份认证 

   web 服务可以在返回 http 响应时附带认证要求 challenge,作用是询问 http 请求的发起方是谁,这时发起方应提供正确的用户名和密码(即认证信息),然后 web 服务才会返回真正的 http 响应。

        收到认证要求时, NSURLConnection 的委托对象会收到相应的消息并得到一个  NSURLAuthenticationChallenge 实例。该实例的发送方遵守 NSURLAuthenticationChallengeSender 协议。为了继续收到真实的数据,需要向该发送方向发回一个  NSURLCredential 实例。代码示例如下:


方法来自:NSURLConnectionDelegate

- ( 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 senderuseCredential:newCred
           forAuthenticationChallenge:challenge];
}

     如果是更复杂,安全要求更高的 web 服务,可能会要求请求的发送方提供一张或多张证书以确认身份。不过多数 web 服务只需要提供用户名和密码。

     程序可以保留 credential, 并有以下三种保留模式。
  • NSURLCredentialPersistenceNone :要求 URL 载入系统 “在用完相应的认证信息后立刻丢弃”。
  • NSURLCredentialPersistenceForSession :要求 URL 载入系统 “在应用终止时,丢弃相应的 credential ”。
  • NSURLCredentialPersistencePermanent :要求 URL 载入系统 "将相应的认证信息存入钥匙串(keychain),以便其他应用也能使用。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值