5

我希望我的应用程序对设备进行身份验证,即通过 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 字符串。

谢谢急诊室

4

2 回答 2

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
      }
  }
}
于 2012-04-08T14:44:35.010 回答
0

您必须使用NSURLConnectionDelegate委托来处理NSURLConnection事件。

对于身份验证,有两种委托方法:connection:canAuthenticateAgainstProtectionSpace:connection:didReceiveAuthenticationChallenge:

请参阅URL 加载系统编程指南中的示例

于 2012-04-08T14:40:38.227 回答