AFNetworking 2.0和HTTP基本身份验证

时间:2013-09-30 19:37:39

标签: ios7 http-authentication afnetworking-2

在AFNetworking 2.0上找不到AFHTTPClient,使用:

AFHTTPClient *client = [AFHTTPClient clientWithBaseURL:[NSURL URLWithString:@"http://examplewebsite.com]];

[client setAuthorizationHeaderWithUsername:@"username" password:@"password"];

如何在AFNetworking 2.0上进行管理?

3 个答案:

答案 0 :(得分:96)

AFNetworking 2.0新架构使用序列化程序来创建请求和解析响应。 要设置授权标头,首先应初始化替换AFHTTPClient的请求操作管理器,创建序列化程序,然后调用专用方法来设置标头。

例如,您的代码将变为:

AFHTTPRequestOperationManager *manager = [[AFHTTPRequestOperationManager alloc] initWithBaseURL:[NSURL URLWithString:@"http://examplewebsite.com"]];
manager.requestSerializer = [AFHTTPRequestSerializer serializer];
[manager.requestSerializer setAuthorizationHeaderFieldWithUsername:@"userName" password:@"password"];

您应该阅读documentationmigration guide以了解AFNetworking 2.0版附带的新概念。

答案 1 :(得分:15)

以下是使用NSURLCredential对AFNetworking 2.0执行基本HTTP身份验证的示例。与使用AFHTTPRequestSerializer setAuthorizationHeaderFieldWithUsername:password:方法相比,此方法的优点是,您可以通过更改NSURLCredential的persistence:参数自动将用户名和密码存储在钥匙串中。 (见this answer。)

AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];

NSURLCredential *credential = [NSURLCredential credentialWithUser:@"user" password:@"passwd" persistence:NSURLCredentialPersistenceNone];

NSMutableURLRequest *request = [manager.requestSerializer requestWithMethod:@"GET" URLString:@"https://httpbin.org/basic-auth/user/passwd" parameters:nil];

AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
[operation setCredential:credential];
[operation setResponseSerializer:[AFJSONResponseSerializer alloc]];
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
    NSLog(@"Success: %@", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
    NSLog(@"Failure: %@", error);
}];
[manager.operationQueue addOperation:operation];

答案 2 :(得分:6)

正如@gimenete所提到的,当使用@titaniumdecoy凭证方法时,多部分请求将失败,因为这在挑战块中应用,并且当前版本的AFNetworking存在此问题。您可以将身份验证嵌入NSMutableRequest标头

,而不是使用凭据方法
    NSMutableURLRequest *request = [[AFHTTPRequestSerializer serializer] multipartFormRequestWithMethod:@"PUT"  URLString:path parameters:myParams constructingBodyWithBlock: ^(id <AFMultipartFormData>formData) {
                    [formData appendPartWithFileData:imageData name:imageName fileName:imageName mimeType:@"image/jpeg"];
            } error:&error];    
    NSString *authStr = [NSString stringWithFormat:@"%@:%@", [self username], [self password]];
    NSData *authData = [authStr dataUsingEncoding:NSUTF8StringEncoding];
    NSString *authValue = [NSString stringWithFormat:@"Basic %@", [authData base64EncodedString]];
    [request setValue:authValue forHTTPHeaderField:@"Authorization"];

您需要使用第三方BASE64编码库,例如来自Matt Gallaghers pre ARC BASE64 solution的NSData + Base64.h和.m文件