简体   繁体   中英

401 error - Basic Authentication with AFNetworking AFHTTPClient & Tastypie

I'm using AFHTTPClient from AFNetworking to make a call from my IOS app to my server, which is using Django with TastyPie. It's working great when I turn authentication off on the server side; however, when I require authentication and insert the proper username and password into my code, the I receive the following 401 authentication error:

\2012-09-16 00:24:37.877 RESTtest[76909:f803] 
Complex AF: Error Domain=AFNetworkingErrorDomain Code=-1011 
"Expected status code in (200-299), got 401" 
UserInfo=0x686ba00 {AFNetworkingOperationFailingURLResponseErrorKey=<NSHTTPURLResponse: 0x686f130>, 
NSErrorFailingURLKey=http://127.0.0.1:8000/api/v1/shoppinglist, 
NSLocalizedDescription=Expected status code in (200-299), got 401, 
AFNetworkingOperationFailingURLRequestErrorKey=<NSMutableURLRequest http://127.0.0.1:8000/api/v1/shoppinglist>}

Here is my code:

AFAPIClient.h #import "AFHTTPClient.h"

@interface AFAPIClient : AFHTTPClient

-(void)setUsername:(NSString *)username andPassword:(NSString *)password;

+ (AFAPIClient *)sharedClient;

@end

AFAPIClient.m:

#import "AFAPIClient.h"
#import "AFJSONRequestOperation.h"


static NSString * const baseURL = @"http://@127.0.0.1:8000/api/v1";


@implementation AFAPIClient

+ (AFAPIClient *)sharedClient {
    static AFAPIClient *_sharedClient = nil;
    static dispatch_once_t pred;
    dispatch_once(&pred, ^{
        _sharedClient = [[AFAPIClient alloc] initWithBaseURL:[NSURL URLWithString:baseURL]];
        //[_sharedClient setAuthorizationHeaderWithUsername:@"myusername" password:@"mypassword"]; I tried putting the authorization command here
    });

    return _sharedClient;
};

#pragma mark - Methods

-(void)setUsername:(NSString *)username andPassword:(NSString *)password;
{
    [self clearAuthorizationHeader];
    [self setAuthorizationHeaderWithUsername:username password:password];
}

- (id)initWithBaseURL:(NSURL *)url
{
    self = [super initWithBaseURL:url];
    if (!self) {
        return nil;
    }

    [self registerHTTPOperationClass:[AFJSONRequestOperation class]];
    [self setParameterEncoding:AFJSONParameterEncoding];


    //[self setAuthorizationHeaderWithUsername:@"myusername" password:@"mypassword"]; I also tried putting the authorization command here

    // Accept HTTP Header; see http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.1
    [self setDefaultHeader:@"Accept" value:@"application/json"];

    return self;
}


@end

TQViewController.h:

[...]
- (IBAction)sendAFClientRequest:(id)sender {
    //[[AFAPIClient sharedClient] setUsername:@"myusername" andPassword:@"mypassword"];
    [[AFAPIClient sharedClient] getPath:@"shoppinglist" parameters:nil success:^(AFHTTPRequestOperation *operation, id response) {
        NSLog(@"Complex AF: %@", [response valueForKeyPath:@"objects"]);
    } failure:^(AFHTTPRequestOperation *operation, id response) {
        NSLog(@"Complex AF: %@", response);
    }
     ];

}
[...]

I know this isn't a problem with my server or my username/password, as I can authenticate just fine by inserting the username/password into the URL:

@"http://myusername:mypassword@127.0.0.1:8000/api/v1/shoppinglist"

Any help on this would be great. It would be wonderful to be able to use AFHTTPClient without inserting the authentication information directly into the static base URL, which seems completely improper. Thanks in advance!

Based on this: https://github.com/AFNetworking/AFNetworking/issues/426

I override the - (void)getPath:(NSString *)path parameters... method in the AFHTTPClient subclass to look something like this:

- (void)getPath:(NSString *)path parameters:(NSDictionary *)parameters
    success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success
    failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure
{
    NSURLRequest *request = [self requestWithMethod:@"GET" path:path parameters:parameters];
    AFHTTPRequestOperation *operation = [self HTTPRequestOperationWithRequest:request success:success failure:failure];
    [operation setAuthenticationChallengeBlock:^(NSURLConnection *connection, NSURLAuthenticationChallenge *challenge) {
        NSURLCredential *newCredential = [NSURLCredential credentialWithUser:self.username password:self.password persistence:NSURLCredentialPersistenceForSession];
        [challenge.sender useCredential:newCredential forAuthenticationChallenge:challenge];
    }];
    [self enqueueHTTPRequestOperation:operation];
}

It only adds the authentication challenge block to the AFHTTPRequestOpertaion, the rest is the same as the original implementation https://github.com/AFNetworking/AFNetworking/blob/master/AFNetworking/AFHTTPClient.m

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM