iOS加载网页时,Https使用的是自制证书

收到AuthenticationChallenge(质疑认证)的处理

- (void)webView:(WKWebView *)webView didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition disposition, NSURLCredential * _Nullable credential))completionHandler {
    ///
    if ([challenge.protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust]) {
        /// 生成认证凭据
        NSURLCredential *credential = [NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust];
        /// 接受服务器凭据
        completionHandler(NSURLSessionAuthChallengeUseCredential, credential);
    } else {
        completionHandler(NSURLSessionAuthChallengePerformDefaultHandling ,nil);
    }
}

Tips:

  • 认证质疑的类型:

    • NSURLAuthenticationMethodServerTrust App对服务器进行认证
    • NSURLAuthenticationMethodClientCertificate,NSURLAuthenticationMethodNegotiate,NSURLAuthenticationMethodNTLM,NSURLAuthenticationMethodHTTPBasic 服务器对客户端进行的认证
  • 响应质疑的类型(NSURLSessionAuthChallengeDisposition)

    • NSURLSessionAuthChallengeUseCredential 使用指定的凭据
    • NSURLSessionAuthChallengePerformDefaultHandling 默认处理如果没有实现URLSessionDelegate,参数默认忽略
    • NSURLSessionAuthChallengeCancelAuthenticationChallenge 取消认证,会取消URLSessionTask
    • NSURLSessionAuthChallengeRejectProtectionSpace 拒绝认证,并进行下一个认证质疑
  • 生成要是用的凭据

    typedef NS_ENUM(NSUInteger, NSURLCredentialPersistence) {
        NSURLCredentialPersistenceNone, //不需要存储
        NSURLCredentialPersistenceForSession, //保存在会话中,推荐
        NSURLCredentialPersistencePermanent, //保存在keychain中
        NSURLCredentialPersistenceSynchronizable API_AVAILABLE(macos(10.8), ios(6.0), watchos(2.0), tvos(9.0)) //保存在keychain中并同步到iCloud
    };
    
    /// 使用用户名,密码,存储方式生成凭据, persistence; NSURLAuthenticationMethodHTTPBasic类型的认证一般用这种方式生成凭据
    + (NSURLCredential *)credentialWithUser:(NSString *)user password:(NSString *)password persistence:(NSURLCredentialPersistence)persistence;
    
    /// https://www.cnblogs.com/jisa/p/11271600.html 参考链接
    /// 使用标识符和证书生成凭证; NSURLAuthenticationMethodClientCertificate类型认证,通常使用该方法生成凭据
    + (NSURLCredential *)credentialWithIdentity:(SecIdentityRef)identity certificates:(nullable NSArray *)certArray persistence:(NSURLCredentialPersistence)persistence
    
    /// 使用服务器返回的serverTrust生成凭证
    + (NSURLCredential *)credentialForTrust:(SecTrustRef)trust
    
posted @ 2022-09-13 17:46  jisa  阅读(171)  评论(0编辑  收藏  举报