如果您不想为服务器信任或客户端 SSL(很少使用)进行自己的身份验证,您可以忽略与 SSL 身份验证回调相关的委托回调,而是系统将使用钥匙串上的默认证书链来验证要求。
如果您想进行自己的身份验证,例如验证服务器信任是否正确,并且如果您想进行证书固定,那么您可以覆盖didReceiveChallenge
委托回调并明确检查服务器信任。
要进行证书固定,请参阅https://gist.github.com/mdelete/d9dbc320d5de347c2a85
如果您只想进行正常的服务器信任检查,假设服务器具有由作为系统一部分的受信任的 CA 颁发的证书,您可以使用它。
OSStatus err = noErr;
BOOL trusted = NO;
NSURLProtectionSpace * protectionSpace = challenge.protectionSpace;
SecTrustRef serverTrustRef = protectionSpace.serverTrust;
SecTrustResultType trustResult;
//check if the server trust that we got from the server can be trusted by default
err = SecTrustEvaluate(serverTrustRef, &trustResult);
trusted = (err == noErr) && ((trustResult == kSecTrustResultProceed) || (trustResult == kSecTrustResultUnspecified));
if (trusted)
{
[challenge.sender useCredential:[NSURLCredential credentialForTrust:protectionSpace.serverTrust]
forAuthenticationChallenge:challenge];
}
else //if not then warn the user about this and let the user make a decision
{
//Cancel conneciton
[challenge.sender cancelAuthenticationChallenge:challenge];
}