Can I use NSURLCredentialStorage for HTTP Basic Authentication?

后端 未结 4 2074
时光说笑
时光说笑 2020-11-27 10:43

I have a cocoa class set up that I want to use to connect to a RESTful web service I\'m building. I have decided to use HTTP Basic Authentication on my PHP backend like so…<

4条回答
  •  南笙
    南笙 (楼主)
    2020-11-27 11:29

    A synchronous NSURLConnection will absolutely work with NSURLCredentialStorage. Here's how things usually work:

    1. NSURLConnection requests the page from the server
    2. The server replies with a 401 response
    3. NSURLConnection looks to see what credentials it can glean from the URL
    4. If the URL did not provide full credentials (username and password), NSURLConnection will also consult NSURLCredentialStorage to fill in the gaps
    5. If full credentials have still not been determined, NSURLConnection will send the -connection:didReceiveAuthenticationChallenge: delegate method asking for credentials
    6. If the NSURLConnection now finally has full credentials, it retries the original request including authorization data.

    By using the synchronous connection method, you only lose out on step 5, the ability to provide custom authentication. So, you can either pre-provide authentication credentials in the URL, or place them in NSURLCredentialStorage before sending the request. e.g.

    NSURLRequest *request =
      [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://user:pass@example.com"]];
    
    [NSURLConnection sendSynchronousRequest:request returningResponse:NULL error:NULL];
    

    or:

    NSURLCredential *credential = [NSURLCredential credentialWithUser:@"user"
                                                             password:@"pass"
                                                          persistence:NSURLCredentialPersistenceForSession];
    
    NSURLProtectionSpace *protectionSpace = [[NSURLProtectionSpace alloc]
      initWithHost:@"example.com"
      port:0
      protocol:@"http"
      realm:nil
      authenticationMethod:nil];
    
    
    [[NSURLCredentialStorage sharedCredentialStorage] setDefaultCredential:credential
                                                        forProtectionSpace:protectionSpace];
    [protectionSpace release];
    
    NSURLRequest *request =
      [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://example.com"]];
    
    [NSURLConnection sendSynchronousRequest:request returningResponse:NULL error:NULL];
    

提交回复
热议问题