IOS https authentication

前端 未结 2 838
粉色の甜心
粉色の甜心 2021-02-06 12:29

I want my application to authenticate against appliance i.e passing username and password over https.

I looked at few examples and basically build the following:

相关标签:
2条回答
  • 2021-02-06 13:09

    You must use NSURLConnectionDelegate delegate to handle NSURLConnection events.

    For authentication there are two delegates methods:connection:canAuthenticateAgainstProtectionSpace: and connection:didReceiveAuthenticationChallenge:

    See examples in URL Loading System Programming Guide

    0 讨论(0)
  • 2021-02-06 13:19

    When making a request requiring authentication, you will receive a callback to didReceiveAuthenticationChallenge, which you handle as follows:

    -(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
          }
      }
    }
    
    0 讨论(0)
提交回复
热议问题