美文网首页HTTPS相关笔记
[iOS网络请求] - 身份认证

[iOS网络请求] - 身份认证

作者: 小呆鸟 | 来源:发表于2017-03-09 12:47 被阅读0次

    NSURLCredential

    NSURLCredential代表的是一个身份验证证书。URL Loading系统支持3种类型的证书:password-based user credentials, certificate-based user credentials, and certificate-based server credentials。

    NSURLCredential适合大多数的认证请求,因为它可以表示由用户名/密码组合、客户端证书及服务器信任创建的认证信息。

    认证信息有三种持久化选项:

    • NSURLCredentialPersistenceNone :要求 URL 载入系统 “在用完相应的认证信息后立刻丢弃”。
    • NSURLCredentialPersistenceForSession :要求 URL 载入系统 “在应用终止时,丢弃相应的 credential ”。
    • NSURLCredentialPersistencePermanent :要求 URL 载入系统 “将相应的认证信息存入钥匙串(keychain),以便其他应用也能使用。

    为了认证,要创建一个NSURLCredential对象。在提供的authentication challenge的protection space上调用authenticationMethod 方法,可以获取服务器的认证方法。

    if (challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodHTTPBasic) {
    
    }else{
    
    }
    

    NSURLCredential支持的认证方法有:

    • HTTP basic authentication (NSURLAuthenticationMethodHTTPBasic) 需要一个用户名和密码。使用
      credentialWithUser:password:persistence:方法创建NSURLCredential对象。

    • HTTP digest authentication (NSURLAuthenticationMethodHTTPDigest),与basic authentication类似,也需要一个用户名和密码。使用
      credentialWithUser:password:persistence:方法创建NSURLCredential对象。

    • Client certificate authentication (NSURLAuthenticationMethodClientCertificate) 需要system identity和需要与server进行身份验证的所有证书。使用 credentialWithIdentity:certificates:persistence:创建NSURLCredential对象。

    • Server trust authentication (NSURLAuthenticationMethodServerTrust) 需要authentication challenge的protection space提供一个trust。使用credentialForTrust:来创建NSURLCredential对象。
      (Basic、Digest与NTLM认证都是基于用户名/密码的认证。他们认证的响应逻辑是相同的。)

    身份认证原理

    在代码需要向认证的服务器请求资源时,服务器会使用http状态码401进行响应,即访问被拒绝需要验证。NSURLConnection会接收到响应并立刻使用认证challenge的一份副本来发送一条willSendRequestForAuthenticationChallenge:委托消息。过程如下所示:

    20151204151927711.jpg

    代码

    - (void)connection:(NSURLConnection *)connection willSendRequestForAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge{
        //以前的失败次数
        if ([challenge previousFailureCount] == 0) {
            //身份认证的类
            NSURLCredential *newCredential;
            newCredential = [NSURLCredential credentialWithUser:@"账号"
                                                       password:@"密码"
                                                    persistence:NSURLCredentialPersistenceNone];
            [[challenge sender] useCredential:newCredential
                   forAuthenticationChallenge:challenge];
        }else{
            [[challenge sender] cancelAuthenticationChallenge:challenge];
            
        }
    
    }
    

    NSURLAuthenticationChallenge

    NSURLAuthenticationChallenge encapsulates a challenge from a server requiring authentication from the client.
    翻译
    NSURLAuthenticationChallenge封装一个挑战来自客户机的服务器要求身份验证。
    
    authentication challenge — An HTTP or HTTPS response indicating that the server requires authentication information from the client Foundation represents this with the NSURLAuthenticationChallenge class, and it also uses this infrastructure to support custom HTTPS server trust evaluation. An authentication challenge originates from a protection space.
    翻译
    身份验证的挑战——一个HTTP或HTTPS响应表明服务器需要身份验证信息从客户机与NSURLAuthenticationChallenge基金会代表这类,它也使用这种基础设施,以支持自定义HTTPS服务器信任评估。身份验证的挑战源于保护空间。
    

    NSURLSession

    对于NSURLSession,代理对象要实现URLSession:task:didReceiveChallenge:completionHandler:方法。 (怎么请求去网上找 这里就不写了)

    - (void)URLSession:(NSURLSession *)session didReceiveChallenge:(nonnull NSURLAuthenticationChallenge *)challenge completionHandler:(nonnull void (^)(NSURLSessionAuthChallengeDisposition, NSURLCredential * _Nullable))completionHandler{
        //以前的失败次数
        if ([challenge previousFailureCount] == 0) {
            //身份认证的类
            NSURLCredential *newCredential;
            newCredential = [NSURLCredential credentialWithUser:@"账号"
                                                       password:@"密码"
                                                    persistence:NSURLCredentialPersistenceNone];
            [[challenge sender] useCredential:newCredential
                   forAuthenticationChallenge:challenge];
        }else{
            [[challenge sender] cancelAuthenticationChallenge:challenge];
            
        }
    }
    

    AFNetworking

    + (void)post:(NSString *)url params:(NSDictionary *)params success:(void (^)(id json))success failure:(void (^)(NSError *error))failure
    {
        
        AFHTTPSessionManager *mgr = [AFHTTPSessionManager manager];
        mgr.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",@"text/html",@"text/plain", nil];
        [mgr.requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Accept"];
        
        [mgr setTaskDidReceiveAuthenticationChallengeBlock:^NSURLSessionAuthChallengeDisposition(NSURLSession *session, NSURLSessionTask *task, NSURLAuthenticationChallenge *challenge, NSURLCredential *__autoreleasing *credential) {
            if (challenge.previousFailureCount == 0) {
                NSURLCredential *cre = [NSURLCredential credentialWithUser:@"账号"
                                                                  password:@"密码" persistence:NSURLCredentialPersistenceForSession];
                *credential = cre;
                return NSURLSessionAuthChallengeUseCredential;
            } else {
                return NSURLSessionAuthChallengeCancelAuthenticationChallenge;
            }
        }];
        
        [mgr POST:url parameters:params success:^(NSURLSessionDataTask *task, id responseObject) {
            if (success) {
                success(responseObject);
            }
        } failure:^(NSURLSessionDataTask *task, NSError *error) {
            if (failure) {
                failure(error);
            }
        }];
    }
    

    本人新手呆鸟,忘各位老司机多多鞭策,使我快速成长。谢谢观看

    相关文章

      网友评论

        本文标题:[iOS网络请求] - 身份认证

        本文链接:https://www.haomeiwen.com/subject/allwgttx.html