我希望我的应用程序对设备进行身份验证,即通过https传递用户名和密码。
我看了几个例子,基本上构建了以下内容:
-(void)authentication
{
//setting the string of the url taking from appliance IP.
NSString *urlString =[NSString
stringWithFormat:
@"http://%@",appliance_IP.text];
//define the url with the string
NSURL *url = [NSURL URLWithString:urlString];
//creating request
NSURLRequest *request = [NSURLRequest requestWithURL:url];
//setting credential taking from the username and password field
NSURLCredential *credential = [NSURLCredential credentialWithUser:username.text password:password.text persistence:NSURLCredentialPersistenceForSession];
NSURLProtectionSpace *protectionSpace=
[[NSURLProtectionSpace alloc]initWithHost:urlString port:443 protocol:@"https" realm:nil authenticationMethod:nil ];
[[NSURLCredentialStorage sharedCredentialStorage] setDefaultCredential:credential forProtectionSpace:protectionSpace];
[ NSURLConnection sendSynchronousRequest:request returningResponse:NULL error:NULL];
}
由于我使用的示例,我需要更多理解,上面示例中的NSURLConnection不包含用户名和密码如何添加它? 因此,请求还将包含用户名和密码,或者最好传递该信息。目前,请求仅包含 url 字符串。
谢谢的
当发出需要身份验证的请求时,您将收到对 didReceiveAuthenticationChallenge 的回调,该回调的处理方式如下:
-(void)connection:(NSURLConnection *)connection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge
{
if ([challenge.protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust])
{
if ([challenge.protectionSpace.host isEqualToString:MY_PROTECTION_SPACE_HOST])
{
[challenge.sender useCredential:[NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust] forAuthenticationChallenge:challenge];
}
[challenge.sender continueWithoutCredentialForAuthenticationChallenge:challenge];
}
else if ([challenge.protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodHTTPBasic])
{
if ([challenge previousFailureCount] == 0)
{
NSURLCredential *newCredential;
newCredential = [NSURLCredential credentialWithUser:MY_USERNAME
password:MY_PASSWORD
persistence:NSURLCredentialPersistenceForSession];
[[challenge sender] useCredential:newCredential forAuthenticationChallenge:challenge];
}
else
{
[[challenge sender] cancelAuthenticationChallenge:challenge];
// inform the user that the user name and password
// in the preferences are incorrect
NSLog (@"failed authentication");
// ...error will be handled by connection didFailWithError
}
}
}
必须使用委托来处理NSURLConnection
事件NSURLConnectionDelegate
。
对于身份验证,有两种委托方法:connection:canAuthenticateAgainstProtectionSpace:
和 connection:didReceiveAuthenticationChallenge:
请参阅 URL 加载系统编程指南中的示例