我正在尝试学习如何使用NSURLSession处理身份验证挑战。我以前从来没有做过任何与安全网络相关的事情。我一直在阅读苹果NSURLSession Programming Guide的Authentication Challenges and TLS Chain Validation部分,在那里提到了object NSURLCredentialStorage,但在它的参考中,我没有得到关于我为什么应该使用它的进一步描述。
NSURLCredentialStorage和Keychain有什么不同?安全地处理用户名和密码的最好方法应该是什么?我一直在寻找使用NSURLSession和NSURLCredentialStorage或Keychain进行身份验证挑战的示例,但都没有成功,有人能告诉我在哪里可以找到吗?
提前感谢
发布于 2016-02-16 18:03:04
如果您不想为服务器信任或客户端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];
}https://stackoverflow.com/questions/35428815
复制相似问题