[iOS-Foundation] Networking Auth

2016-10-10  本文已影响437人  水止云起

当发送 HTTPS 请求时,在握手阶段服务器可能要求客户端提供证书用来证明身份。或者在 HTTP 协议层,服务器可通过响应头WWW-Authenticate要求验证客户端身份。在使用 URL Loading System 发送网络请求时,当遇到上述情况时,系统会调用 URLSession 对象的代理的
URLSession:didReceiveChallenge:completionHandler:
URLSession:task:didReceiveChallenge:completionHandler:方法。另外在 SSL/TLS 协议中,客户端在握手阶段验证服务器证书时,也会调用上述代理方法。

代理方法中的参数 challenge 是一个NSURLAuthenticationChallenge对象,该类封装了请求验证的信息。所以一般情况下,应用不需要自己创建该类型对象,只有在使用自定义协议时,则可能需要主动创建。

NSURLAuthenticationChallenge

NSURLAuthenticationChallenge 类中最重要的一个属性是protectionSpace,该属性是一个 NSURLProtectionSpace 的实例,一个NSURLProtectionSpace对象通过属性hostisProxyportprotocolproxyTyperealm代表了请求验证的服务器端的范围。而NSURLProtectionSpace类的authenticationMethod属性则指明了服务端的验证方式,可能的值包括

NSURLAuthenticationMethodDefault
// 基本的 HTTP 验证,通过 NSURLCredential 对象提供用户名和密码。
NSURLAuthenticationMethodHTTPBasic
// 类似于基本的 HTTP 验证,摘要会自动生成,同样通过 NSURLCredential 对象提供用户名和密码。
NSURLAuthenticationMethodHTTPDigest
// 不会用于 URL Loading System,在通过 web 表单验证时可能用到。
NSURLAuthenticationMethodHTMLForm
NSURLAuthenticationMethodNegotiate
NSURLAuthenticationMethodNTLM
// 验证客户端的证书
NSURLAuthenticationMethodClientCertificate
// 指明客户端要验证服务端提供的证书
NSURLAuthenticationMethodServerTrust

除了protectionSpaceNSURLAuthenticationChallenge还包括以下几项属性:

NSURLSessionAuthChallengeDisposition

NSURLSession的代理方法中执行相应的逻辑后,需调用代理方法的 block 参数 completionHandler,来通知系统如何处理验证。该 block 需要传入两个参数,NSURLSessionAuthChallengeDisposition类型的 disposition,说明处理的方式,另一个参数是对应的NSURLCredential对象。
NSURLSessionAuthChallengeDisposition可能的值包括:

// 指明通过另一个参数 credential 提供证书
NSURLSessionAuthChallengeUseCredential
// 相当于未执行代理方法,使用默认的处理方式,不使用参数 credential
NSURLSessionAuthChallengePerformDefaultHandling
// 拒绝该 protectionSpace 的验证,不使用参数 credential
NSURLSessionAuthChallengeRejectProtectionSpace
// 取消验证,不使用参数 credential
NSURLSessionAuthChallengeCancelAuthenticationChallenge

NSURLCredential

当 disposition 的值为 NSURLSessionAuthChallengeUseCredential时,需要提供一个 NSURLCredential 对象。可以创建3种类型的 Credential:

// 当 protectionSpace 的 authenticationMethod 的值为 NSURLAuthenticationMethodHTTPBasic 或 NSURLAuthenticationMethodHTTPDigest 时
+ credentialWithUser:password:persistence:
- initWithUser:password:persistence:
// 当 protectionSpace 的 authenticationMethod 的值为 NSURLAuthenticationMethodClientCertificate 时
+ credentialWithIdentity:certificates:persistence:
- initWithIdentity:certificates:persistence:
// 当 protectionSpace 的 authenticationMethod 的值为 NSURLAuthenticationMethodServerTrust 时
+ credentialForTrust:
- initWithTrust:

另外,可通过 NSURLCredentialStorage 管理。

上一篇 下一篇

猜你喜欢

热点阅读