NSURLConnection将发送请求认证挑战安全
问题描述:
我在iOS应用中使用HTTPS POST连接到内部公司REST服务。 此服务需要基本的HTTP身份验证。NSURLConnection将发送请求认证挑战安全
当我尝试在HTTPHeader中传递身份验证参数时,服务器回应并返回错误消息,说“错误域= NSURLErrorDomain代码= -1202”此服务器的证书无效。您可能会连接到假装为“oiam.XXXX.com”的服务器,这可能会使您的机密信息处于危险之中。“UserInfo = 0x8d1de60 {NSErrorFailingURLStringKey = https://oiam.xxxx.com/NSLocalizedRecoverySuggestion=Would您想要连接到服务器吗?”,
我读了一些问题,看起来像我需要安装证书。由于我在iOS模拟器上,因此无法安装证书。
我试图使用NSURLConnectionDelegate协议和连接工作。
唯一的问题是我有这种方法,我通过用户名密码。它安全吗?为什么我不需要对值进行编码?我在进行Header中的HTTPS基本身份验证时传递值。
-(void)connection:(NSURLConnection *)connection willSendRequestForAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge {
if ([challenge previousFailureCount]) {
[[challenge sender] cancelAuthenticationChallenge:challenge];
} else {
NSURLCredential *credential = [NSURLCredential credentialWithUser:@"username1"
password:@"password1"
persistence:NSURLCredentialPersistenceForSession];
[[challenge sender] useCredential:credential forAuthenticationChallenge:challenge];
}
}
答
供内部使用和测试,你可以使用类扩展在NSURLRequest
覆盖私有API,使得无效的证书被接受:
#if DEBUG
@interface NSURLRequest (IgnoreSSL)
+ (BOOL)allowsAnyHTTPSCertificateForHost:(NSString *)host;
@end
@implementation NSURLRequest (IgnoreSSL)
+ (BOOL)allowsAnyHTTPSCertificateForHost:(NSString *)host
{
// ignore certificate errors only for this domain
if ([host hasSuffix:@"oiam.XXXX.com"]) {
return YES;
}
else {
return NO;
}
}
@end
#endif
至于有关凭据的安全性问题,它们将在通过电线传输之前根据需要进行编码。
谢谢。我现在使用HTTPS Basic Auth(在Header中传递证书)并从Stack Overflow添加了这个代码以删除证书错误: - (void)connection:(NSURLConnection *)连接willSendRequestForAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge if [[[challenge认证方法] == NSURLAuthenticationMethodServerTrust){[challenge sender] useCredential:[NSURLCredential credentialForTrust:[[challenge protectionSpace] serverTrust]] for challenge authentication:challenge]; }}它的工作。我试图弄清楚这是什么。 – Jasmine
@Jasmine你可以把整个代码用于willSendRequestForAuthenticationChallenge,所以我对它有了更多的了解。为你+1。 –
@DhavalBhadania我现在正在使用neilco的建议。它适用于任何自签名证书的开发。我只是忽略了错误。在签发证书时的生产中,我摆脱了NSURLRequest(IgnoreSSL)文件。 – Jasmine