2

我正在尝试学习如何使用NSURLSession. 我以前从未做过与安全网络相关的任何事情。我一直在阅读Apple 的Authentication Challenges and TLS Chain ValidationNSURLSession Programming Guide部分,并在其中提到了该对象NSURLCredentialStorage,但在其参考资料中,我没有进一步描述我为什么要使用它。

NSURLCredentialStorage和 和有什么不一样Keychain?安全处理用户名和密码的最佳方法是什么?我一直在寻找一个身份验证挑战的例子,无论NSURLSession是成功还是失败,有人能告诉我在哪里可以找到一个吗?NSURLCredentialStorageKeychain

提前致谢

4

1 回答 1

2

如果您不想为服务器信任或客户端 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];

}
于 2016-02-16T10:03:03.827 回答