Sta*_*ros 8 iphone cocoa nsurlconnection nsurlrequest nsurlcredential
大家早上好,
我一直在尝试编写一个从需要身份验证的远程Web服务执行某些GET的应用程序.我的主要问题是这些远程服务器中的大多数(并且有很多远程服务器)没有有效的证书.我有代码接受无效的证书和代码,以正确的uname&pass(下面)来响应挑战.我遇到的问题是让两人一起玩.我似乎无法找到一种方法来发送挑战NSURLCredential
或正确链接回调的方法.当我试图将它们连接起来时,我无法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;
}
}
}
Run Code Online (Sandbox Code Playgroud)
您只能回复NSURLAuthenticationChallenge
带有该挑战的凭据.您可以使用以下方法确定您收到的挑战类型:
[[challenge protectionSpace] authenticationMethod]
Run Code Online (Sandbox Code Playgroud)
这里记录了可能的值.如果服务器证书无效,则验证方法为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];
}
Run Code Online (Sandbox Code Playgroud)
如果您每次都没有同时获得两次身份验证,那么这不是错误.您可以在创建凭据时缓存凭据.如果这样做,则不一定会再次提示您.
归档时间: |
|
查看次数: |
3821 次 |
最近记录: |