Search code examples
iosobjective-chttprequestafnetworkingbasic-authentication

AFNetworking http basic authentication gives error "Your API key was not formatted properly"


Trying to use the postmates api, but running into issues with authorization.

To quote their site:

AUTHENTICATION

The Postmates API requires authentication by HTTP Basic Auth headers. Your API key should be included as the username. The password should be left empty.

The actual header that is used will be a base64-encoded string like this:

Basic Y2YyZjJkNmQtYTMxNC00NGE4LWI2MDAtNTA1M2MwYWYzMTY1Og==

I tried using AFNetworking like so

AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];

NSURLCredential *credential = [NSURLCredential credentialWithUser:@"(my postmates key)" password:@"" persistence:NSURLCredentialPersistenceNone];

NSMutableURLRequest *request = [manager.requestSerializer requestWithMethod:@"GET" URLString:@"https://api.postmates.com/v1/delivery_zones" 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];    

The error message I'm getting is

   Incorrect NSStringEncoding value 0x0000 detected. Assuming NSASCIIStringEncoding. Will stop this compatiblity mapping behavior in the near future.

 Success: {
        code = "invalid_authorization_header";
        kind = error;
        message = "Your API key was not formatted properly";
    }

Solution

  • Instead of creating a credential, you might want to try:

    [request setValue:@"Basic Y2YyZjJkNmQtYTMxNC00NGE4LWI2MDAtNTA1M2MwYWYzMTY1Og==" forHTTPHeaderField:@"Authorization"];