【原创】NSURLSession HTTPS Mutual Authentication

1.引入<NSURLSessionDelegate>协议

2.登录验证请求

-(void)authenticate
{
    NSURL *url = [NSURL URLWithString:authAddress];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    request.HTTPMethod = @"GET";
    NSString *userString = @"name:password";
    NSData *userData = [userString dataUsingEncoding:NSUTF8StringEncoding];
    NSString *base64String = [userData base64EncodedStringWithOptions:NSDataBase64EncodingEndLineWithLineFeed];
    [request setValue:[NSString stringWithFormat:@"Basic %@",base64String] forHTTPHeaderField:@"Authorization"];

    NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration] delegate:self delegateQueue:[NSOperationQueue mainQueue]];
    NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {

    }];
    [task resume];
}

3.NSURLSessionDelegate回调

#pragma mark -- NSURLSessionDelegate
- (void)URLSession:(NSURLSession *)session didReceiveChallenge:(NSURLAuthenticationChallenge *)challenge completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition, NSURLCredential * _Nullable))completionHandler
{
    if ([challenge.protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodClientCertificate])//Client Authentication
    {
        NSURLCredential *credential = [NSURLCredential credentialWithUser:@"name" password:@"password" persistence:NSURLCredentialPersistenceForSession];
        completionHandler(NSURLSessionAuthChallengeUseCredential,credential);
    }
    else if ([challenge.protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust])//Server Authentication
    {
        SecTrustRef serverTrust = challenge.protectionSpace.serverTrust;
        SecCertificateRef serverCertificate = SecTrustGetCertificateAtIndex(serverTrust, 0);
        NSData *serverData = (__bridge_transfer NSData*)SecCertificateCopyData(serverCertificate);
        NSData *localData = [NSData dataWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"cert" ofType:@"cer"]];
        if ((!localData) || [serverData isEqualToData:localData])
        {
            NSURLCredential *credential = [NSURLCredential credentialForTrust:serverTrust];
            [challenge.sender useCredential:credential forAuthenticationChallenge:challenge];
            completionHandler(NSURLSessionAuthChallengeUseCredential,credential);
        }
        else
        {
            completionHandler(NSURLSessionAuthChallengeCancelAuthenticationChallenge,nil);
        }
    }
    else
    {
        completionHandler(NSURLSessionAuthChallengeCancelAuthenticationChallenge,nil);
    }
}

注意:NSURLAuthenticationMethodClientCertificate为客户端证书验证,有p12证书的话需要使用此证书进行认证,方法参考此文章;NSURLAuthenticationMethodServerTrust为服务端验证,我们需要用本地证书与服务端返回的挑战的serverTrust获得的证书数据进行比对,如果判断为同一证书,则响应挑战;特别要注意的是,协议回调会触发两次,分别为以上两种验证挑战,如有其它类型挑战则取消本次验证

各位大神如有好的经验希望分享出来~我也是在学习中

p.p1 { margin: 0.0px 0.0px 0.0px 0.0px; font: 18.0px Menlo; color: #6122ae }
span.s1 { color: #000000 }
span.s2 { }
p.p1 { margin: 0.0px 0.0px 0.0px 0.0px; font: 18.0px Menlo; color: #822d0f }
span.s1 { }

时间: 2024-10-11 00:16:34

【原创】NSURLSession HTTPS Mutual Authentication的相关文章

[转] An Introduction to Mutual SSL Authentication

1. Introduction Mutual SSL authentication or certificate based mutual authentication refers to two parties authenticating each other through verifying the provided digital certificate so that both parties are assured of the others' identity. In techn

An Introduction to Mutual SSL Authentication

1. Introduction Mutual SSL authentication or certificate based mutual authentication refers to two parties authenticating each other through verifying the provided digital certificate so that both parties are assured of the others' identity. In techn

编译安装Apache HTTP Server 2.4.23 以及配置HTTP/HTTPS反向代理

编译安装Apache HTTP Server 2.4.23以及配置HTTP/HTTPS反向代理一,依赖软件: 1.1 GCC和C++编译器 GCC C++ Compiler 1.1.1 如果没有安装以上依赖包请执行以下命令安装: [[email protected] ~]# yum install -y gcc gcc-c++ 1.1.2 如果已经安装其中一个,可以单独执行以下命令安装其中一个: [[email protected] ~]# yum install -y gcc[[email p

【HTTPS】什么是SSL,HTTPS是如何工作的?

引言 我们大多数人每天都使用加密通信,你可能不知道,甚至从每关心它.如你用百度搜索东西,你在阿里巴巴上买了一件喜欢的衬衫,HTTPS能防止你的数据在网络传输过程中不被其他人窃取. 在本博客中,我们将介绍我们加密通信背后的知识,主要内容包括:为什么我们需要升级HTTP到HTTPS,HTTP的问题在哪里?TSL和SSL探讨,HTTPS是什么?HTTPS是如何工作的?从黑客的角度如何攻击HTTPS等. 在阅读本文之前,作者默认了你已经对称加密,非对称加密,摘要算法已经有所了解,如果实在没有基础也没关系

kerberos (https://en.wikipedia.org/wiki/Kerberos_(protocol))

Protocol[edit] Description[edit] The client authenticates itself to the Authentication Server (AS) which forwards the username to a key distribution center(KDC). The KDC issues a ticket-granting ticket (TGT), which is time stamped, encrypts it using

树莓派安装wiringPi脚本(原创)

博主原创:https://i.cnblogs.com/EditPosts.aspx?opt=1 wiringPi.sh 1 #!/bin/sh 2 cd / 3 echo "安装git-core" 4 sudo apt-get install git-core 5 echo "下载winringPi库" 6 git clone git://git.drogon.net/wiringPi 7 echo "编译和安装库" 8 cd wiringPi

MongoDB 3.6 Authentication IP Restrictions

前言 好了,看了这个标题,我不知道你有没有一种潜意识,如果有,没错,那就是这个了,MongoDB 终于开放了我觉得对于一个数据库的安全来说,比较重要的一个模块了 --- IP 白名单. 众所周知,MySQL.Oracle.SqlServer等知名的数据库都是有在安全方面作出相当的防护的. IP白名单 针对库.表的权限区分 针对不同的增删改查.事务.admin等的权限分配 甚至于Oracle还提供了针对于不同权限所组合而成的逻辑角色,MySQL在这方面也做了相应的调整. 但是回过头来看看Mongo

WCF Security基本概念(转载)

WCF Security 主要包括 "Transfer Security"."Access Control"."Auditing" 几个部分. 1. Transfer Security Transfer Security 主要包括三个方面: "消息完整性(Message Integrity)"."消息机密性 (Message Confidentiality)" 和 "交互验证(Mutual Aut

WCF Security(转载)

WCF Security 主要包括 "Transfer Security"."Access Control"."Auditing" 几个部分. 1. Transfer Security Transfer Security 主要包括三个方面: "消息完整性(Message Integrity)"."消息机密性 (Message Confidentiality)" 和 "交互验证(Mutual Aut