当我们尝试使用NSURLConnection连接SSL以获取不受信任的证书时,是否有办法让用户选择是否信任该站点?

时间:2013-07-23 19:29:30

标签: ios nsurlconnection ssl-certificate nsurlconnectiondelegate

堆栈溢出时有类似的question

这是我的代码,无论如何都会接受不受信任的服务器证书。

- (BOOL)connection:(NSURLConnection *)connection canAuthenticateAgainstProtectionSpace:(NSURLProtectionSpace *)space
{
    //We can always attempt to authenticate...
    return YES;
}

- (void)connection:(NSURLConnection *)connection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge
{
    if ([[challenge protectionSpace] authenticationMethod] == NSURLAuthenticationMethodServerTrust) {
        [[challenge sender] useCredential:[NSURLCredential credentialForTrust:[[challenge protectionSpace] serverTrust]] forAuthenticationChallenge:challenge];
    } else {
      // Other situation
    }
}

但是,我想提供一个更改视图,让用户选择是否信任该网站。

UIAlertView *alert = [[UIAlertView alloc] initWithTitle:
[[challenge protectionSpace]host] message:@"Do you trust this site?" 
delegate:self cancelButtonTitle:@"No" 
otherButtonTitles:@"Yes", @"Just once", nil];

[alert show];

我该怎么做?

1 个答案:

答案 0 :(得分:0)

作为示例,您可以将质询对象保存到属性,然后像这样实现alertView:clickedButtonAtIndex:委托方法(这是“信任一次”):

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if(buttonIndex == alertView.cancelButtonIndex)
    {
        [[self.challenge sender] cancelAuthenticationChallenge:self.challenge];
    }
    else
    {
        [self.challenge.sender useCredential:[NSURLCredential credentialForTrust:self.challenge.protectionSpace.serverTrust] forAuthenticationChallenge:self.challenge];
        self.challenge = nil;
    }
}

如果您想要始终信任,则需要执行一些更复杂的操作来保存和比较服务器证书数据。或者通过保存服务器URL应始终受信任使其简单且不安全,这使您在中间攻击中容易受到攻击。