iPhone: How to Get Basic Authentication to HTTPS Web Service Using NSURLCredential

Posted by ian1971 on Stack Overflow See other posts from Stack Overflow or by ian1971
Published on 2010-02-24T13:52:31Z Indexed on 2010/03/12 8:27 UTC
Read the original article Hit count: 875

I am trying to call an https web service (RESTful) using basic authentication. It works fine if I put the credentials in the url itself but I would rather add it to the request so that the password does not appear, for instance in an exception.

I am using the following code:

    NSURLCredential *credential = [NSURLCredential credentialWithUser:@"myuser"
                                                             password:@"mypassword"
                                                          persistence:NSURLCredentialPersistenceForSession];

    NSURLProtectionSpace *protectionSpace = [[NSURLProtectionSpace alloc]
                                             initWithHost:@"example.com"
                                             port:443
                                             protocol:@"https"
                                             realm:nil
                                             authenticationMethod:NSURLAuthenticationMethodHTTPBasic];


    [[NSURLCredentialStorage sharedCredentialStorage]  setDefaultCredential:credential
                                                        forProtectionSpace:protectionSpace];

    NSURLConnection *theConnection = [NSURLConnection  connectionWithRequest:theRequest delegate:self];

but it does not work. The didReceiveAuthenticationChallenge delegate method gets called and I can add a credential there but ideally I would send it with the request.

Any ideas?

© Stack Overflow or respective owner

Related posts about iphone

Related posts about cocoa-touch