我希望我的应用程序对设备进行身份验证,即通过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字符串。
由于 ER
答案 0 :(得分:8)
在提出要求身份验证的请求时,您将收到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
}
}
}
答案 1 :(得分:0)
您必须使用NSURLConnectionDelegate
委托来处理NSURLConnection
个事件。
对于身份验证,有两种委托方法:connection:canAuthenticateAgainstProtectionSpace:
和connection:didReceiveAuthenticationChallenge: