【发布时间】:2011-06-29 23:47:21
【问题描述】:
我想向 a previously posed question 提出后续问题。我有创建 NSURLRequest/Connection 的代码,运行它并调用用于身份验证的回调方法。具体代码如下:
- (BOOL)connection:(NSURLConnection *)connection canAuthenticateAgainstProtectionSpace:(NSURLProtectionSpace *)protectionSpace {
return [protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust] || [protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodDefault];
}
-(void)connection:(NSURLConnection *)connection
didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge
{
if ([challenge previousFailureCount] > 0) {
[[challenge sender] cancelAuthenticationChallenge:challenge];
NSLog(@"Bad Username Or Password");
badUsernameAndPassword = YES;
finished = YES;
return;
}
if ([challenge.protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust])
{
if (appDelegate._allowInvalidCert)
{
// Go ahead...trust me!
[challenge.sender useCredential:
[NSURLCredential credentialForTrust: challenge.protectionSpace.serverTrust]
forAuthenticationChallenge: challenge];
}
else
{
TrustGenerator *tg = [[TrustGenerator alloc] init];
if ([tg getTrust:challenge.protectionSpace])
{
// Go ahead...trust me!
[challenge.sender useCredential:
[NSURLCredential credentialForTrust: challenge.protectionSpace.serverTrust]
forAuthenticationChallenge: challenge];
}
else {
[[challenge sender] cancelAuthenticationChallenge:challenge];
}
}
}
else if ([[challenge protectionSpace] authenticationMethod] == NSURLAuthenticationMethodDefault) {
NSURLCredential *newCredential = [NSURLCredential credentialWithUser:_username password:_password persistence:NSURLCredentialPersistenceNone];
[[challenge sender] useCredential:newCredential forAuthenticationChallenge:challenge];
}
}
我遇到的是带有“[challenge.protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust]”的“didReceiveAuthenticationChallenge”总是被调用,即使我正在尝试服务器上的证书连接到是受信任的(使用 Verisign 证书进行测试)。所以我看到的是我的应用程序总是提示最终用户信任,即使网站是受信任的。考虑到这是一个人在中间攻击时会发生的事情,等等。我真正想要的是这样的代码:
if (appDelegate._allowInvalidCert)
{
// Go ahead...trust me!
[challenge.sender useCredential:
[NSURLCredential credentialForTrust: challenge.protectionSpace.serverTrust]
forAuthenticationChallenge: challenge];
}
else if(The OS trusts the cert on the server)
{
[challenge.sender useCredential:
[NSURLCredential credentialForTrust: challenge.protectionSpace.serverTrust]
forAuthenticationChallenge: challenge];
}
else{...
【问题讨论】:
-
好帖子!我在哪里可以找到
TrustGenerator代码?
标签: iphone cocoa-touch ios certificate nsurlconnection