使用AFHTTPClient和Cookie身份验证

时间:2012-05-23 16:06:30

标签: ios cocoa authentication nsurlconnection afnetworking

我的应用程序从使用基于表单的身份验证的网站提取数据。它需要透明地响应重定向到登录页面&通过POST请求提供所请求的凭据。

我之前使用过ASIHTTPREQUEST&然后经历了检查网址的过程,看看我是否已被重定向到身份验证页面&如果是这样发送POST请求与登录表单变量&然后再次提出原始请求。它有效,但有点像黑客。

我现在正将代码转移到AFNetworking&想知道是否有更优雅的方式实现这一点,也许注入一个auth标头?在重定向到auth页面时,让AFHTTPClient触发认证委托方法&然后张贴表格。这里有一些伪代码:

- (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];
    }
}

1 个答案:

答案 0 :(得分:3)

让自己轻松自如,并使用HTTP提供的功能。

HTTP定义status codes,告诉您请求是否成功(200)或者是否需要授权(401)。

将您的凭据存储在共享Authorized实例的AFHTTPClient HTTP header中,并且您将对所有后续呼叫进行身份验证。

或者,如果他们没有这样做,您可以使用AFURLConnection -setAuthenticationChallengeBlock:来应对身份验证挑战。

相关问题