lidders
lidders

Reputation: 140

Using AFHTTPClient with Cookie authentication

My app pulls data from a website which uses Form based authentication. It needs to transparently react to a redirection to the login page & provide the requested credentials via a POST request.

I've previously used ASIHTTPREQUEST & then gone through a process of checking the url to see if I've been redirected to the authentication page & if so sending the POST request with the login form variables & then making the original request again. It works but is a bit of a hack.

I'm presently moving my code over to AFNetworking & wondering if there is a more elegant way of achieving this, perhaps injecting an auth header? to get AFHTTPClient to trigger the authentication delegate methods when a redirect to the auth page occurs & then posting the form. Here's a bit of pseudo code:

- (void)requestFinished:(ASIHTTPRequest *)request {
if ([Connection isAuthURL:[request url]])
{
    // If so have we just tried to login ?
    if ( requestState == requestStateSendingLoginCredentials )
    {
        // Login Failed - tried to login & been redirected back to login page
        [self requestFailed:request];
    }
    else
    {
        // We have been directed to login page after a page request
        requestState = requestStateSendingLoginCredentials
        [self postLoginForm:request];
    }
}
else 
{ // Not the authentication page
    if ( requestState == requestStateSendingLoginCredentials )
    {   // We must have successfully logged in
        requestState = requestStateSuccessful;
        // If it was a form we need to post again now were logged in.
        if ([lastRequest isAForm])
        {
            // If original request that triggered the login was a POST request
            // we have to re-send it.
            [self requestURL:nil]; // This will send the last request again
            return;
        }
    }
    if (requestState == requestStateSuccessful)
    {
        [self processResponse:request];
    }
}

Upvotes: 1

Views: 2253

Answers (1)

mattt
mattt

Reputation: 19544

Make things easy on yourself and use what HTTP gives you.

HTTP defines status codes that tell you whether a request was successful (200) or if they require authorization (401).

Store your credentials in an Authorized HTTP header for your shared AFHTTPClient instance, and you'll be authenticated for all subsequent calls.

Or, if those aren't doing it, you can use AFURLConnection -setAuthenticationChallengeBlock: to respond to authentication challenges.

Upvotes: 3

Related Questions