大家早上好,

我一直在尝试编写一个从需要身份验证的远程Web服务中获取的应用程序。我的主要问题是,这些远程服务器中的大多数(其中很多)没有有效的证书。我有 代码接受无效的证书 和代码以正确的UNAME&PASS(下)应对挑战。我遇到的问题是让两者一起玩。我似乎找不到将挑战发送挑战的方法 NSURLCredentialS或正确链回回电的方法。当我尝试链接它们时,我无法得到我的 NSURLRequest 打电话 didReceiveAuthenticationChallenge 两次。

任何想法都将不胜感激!

身份验证的代码...

-(void)connection:(NSURLConnection *)connection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge
{   
    if(!hasCanceled){
        if ([challenge previousFailureCount] == 0) {
            NSURLCredential *newCredential;
            newCredential=[NSURLCredential credentialWithUser:_username password:_password persistence:NSURLCredentialPersistenceNone];
            [[challenge sender] useCredential:newCredential forAuthenticationChallenge:challenge];
        } 
        else {
            [[challenge sender] cancelAuthenticationChallenge:challenge];
            NSLog(@"Bad Username Or Password");
            badUsernameAndPassword = YES;
            finished = YES;
        }
    }
}
有帮助吗?

解决方案

您只能回复 NSURLAuthenticationChallenge 有了这一挑战的证书。您可以确定收到的挑战类型:

[[challenge protectionSpace] authenticationMethod]

可能的值是 在这里记录. 。对于无效的服务器证书,身份验证方法将是 NSURLAuthenticationMethodServerTrust. 。在您的代码中,您应该检查身份验证方法并适当响应。

if ([challenge previousFailureCount] > 0) {
    // handle bad credentials here
    [[challenge sender] cancelAuthenticationChallenge:challenge];
    return;
}

if ([[challenge protectionSpace] authenticationMethod] == NSURLAuthenticationMethodServerTrust) {
    // check if the user has previously accepted the certificate, otherwise prompt
} else if ([[challenge protectionSpace] authenticationMethod] == /* your supported authentication method here */) {
    [[challenge sender] useCredential:/* your user's credential */ forAuthenticationChallenge:challenge];
}

如果您每次都没有两种身份验证挑战,这不是错误。创建它们时可以缓存凭据。如果这样做,您将不一定会再次提示。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top