0

堆栈溢出也有类似的问题

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

- (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];

我怎样才能做到这一点?

4

1 回答 1

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 使其变得简单和不安全,这使您容易受到中间人攻击。

于 2013-12-10T09:55:13.150 回答