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, );
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获得的证书数据进行比对,如果判断为同一证书,则响应挑战;特别要注意的是,协议回调会触发两次,分别为以上两种验证挑战,如有其它类型挑战则取消本次验证
各位大神如有好的经验希望分享出来~我也是在学习中