Wednesday, January 13, 2016

Objective C NSURLConnection authentication challenge

Usually we pass user credentials for a service request as GET parameters or POST parameters. But some services or some URLs ask credentials in a popup. You might have noticed some sites ask your login credentials in a popup window which comes from top of the browser. This type of authentication is called as NTLM authentication.

If we need to call a service which resides on a NTLM authenticated server, then we can't pass credentials as GET or POST parameters. Because it asks credentials after the service hit to a URL. So the question here is 

How to pass user credentials after the service hit?

Don't worry. We have a built in delegate method of NSURLConnection to solve this need.

NSURLConnection is having a delegate method called willSendRequestForAuthenticationChallenge, which will be called whenever a service ask you for an authentication at rum time. This delegate method is shown below.




This delegate method is clearly saying something. That is the connection you have requested using NSURLConnection is having an authentication challenge. All we have to do in this delegate method is to provide the user credentials to the authentication challenge sender which is prompting you to provide the credentials.

Now the question is how to pass the credentials? and in which format? This delegate method is not having a return value even. 

Here how it is.




Using NSURLCredential, we can pass the username and password of the user along with our required persistence. We are passing this NSURLCredential object to the authentication challenge sender.

Here is the list of all credential persistence types.

    NSURLCredentialPersistenceNone,
    NSURLCredentialPersistenceForSession,
    NSURLCredentialPersistencePermanent,
    NSURLCredentialPersistenceSynchronizable NS_ENUM_AVAILABLE(10_8, 6_0)



Hope this post is useful. Feel free to comment incase of any queries.