如何使用RestKit进行NTLM身份验证

时间:2012-05-07 11:17:18

标签: ios restkit ntlm

NTLM authentication是否支持RestKit?我如何在我的项目中使用它?

2 个答案:

答案 0 :(得分:0)

目前,RestKit不支持NTML身份验证,但有一种解决方法: 1.在登录页面中,使用NSURLRequest加载请求身份验证的URL并注册身份验证委托:

    - (void) connection:(NSURLConnection *)connection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge
{
    if ([[challenge protectionSpace] authenticationMethod] == NSURLAuthenticationMethodNTLM)
    {
        /*    This is very, very important to check.  Depending on how your security policies are setup, you could lock your user out of his or her account by trying to use the wrong credentials too many times in a row.    */
        if ([challenge previousFailureCount] > 0)
        {
            [[challenge sender] cancelAuthenticationChallenge:challenge];

            UIAlertView* alert = [[UIAlertView alloc] initWithTitle:@"Invalid Credentials" message:@"The credentials you saved for your account are invalid." delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
            [alert show];
            [alert release];
        }
        else
        {
            [[challenge sender]  useCredential:[NSURLCredential credentialWithUser:@"someUser" password:@"somePassword" persistence:NSURLCredentialPersistenceForSession] forAuthenticationChallenge:challenge];
        }
    }
    else
    {
        //    Do whatever you want here, for educational purposes, I'm just going to cancel the challenge
        [[challenge sender] cancelAuthenticationChallenge:challenge];
    }
}

在其他页面中,您可以正常使用RestKit而无需身份验证。我只是用SharePoint服务器测试它,因为它在cookie中保持身份验证,不确定它是否与其他人一起使用。

玩得开心! :)

Ps:How to do NTLM Authentication in iOS

答案 1 :(得分:0)

我必须继承RKObjectManager并覆盖getObjectsAtPath:

- (void)getObjectsAtPath:(NSString *)path
          parameters:(NSDictionary *)parameters
             success:(void (^)(RKObjectRequestOperation *operation, RKMappingResult *mappingResult))success
             failure:(void (^)(RKObjectRequestOperation *operation, NSError *error))failure
{
    NSParameterAssert(path);
    RKObjectRequestOperation *operation = [self appropriateObjectRequestOperationWithObject:nil method:RKRequestMethodGET path:path parameters:parameters];
    [operation setCompletionBlockWithSuccess:success failure:failure];

    //this is the part to handle ntlm authentication, which we arent able to do in RKObjectManager
    [[operation HTTPRequestOperation] setAuthenticationChallengeBlock:^(NSURLConnection *connection, NSURLAuthenticationChallenge *challenge) {
        NSURLCredential *credential = [NSURLCredential credentialWithUser:@"username" password:@"password" persistence:NSURLCredentialPersistenceForSession];
        [[challenge sender] useCredential:credential forAuthenticationChallenge:challenge];
    }];

    [self enqueueObjectRequestOperation:operation];
}