Search code examples
iosasihttprequestbasic-authentication

ASIHTTPRequest Basic Authentication failing


I am using the following code:

NSString *params = [NSString stringWithFormat:@"{\"username\": \"%@\", \"password\": \"%@\", \"client_id\": \"%@\", \"client_secret\": \"%@\"}",
                    mFieldUsername.text, mFieldPassword.text, [NTDefaults clientId], [NTDefaults clientSecret]];
NSLog(@"Params:\n%@", params);

NSURL *url = [NSURL URLWithString:[[NTDefaults baseEndpointUrl] stringByAppendingString:@"/api/token.json"]];
ASIHTTPRequest *request = [ASIFormDataRequest requestWithURL:url];
[request addRequestHeader:@"Content-Type" value:@"application/json"];
[request addRequestHeader:@"Content-Length" value:[NSString stringWithFormat:@"%d",params.length]];
[request setAuthenticationScheme:(NSString *) kCFHTTPAuthenticationSchemeBasic];
[request setUsername:@"user"];
[request setPassword:@"pass"];
[request setShouldPresentCredentialsBeforeChallenge:YES];

[request setPostBody:[params dataUsingEncoding:NSUTF8StringEncoding]];

NSLog(@"Post Body: %@", request.postBody);
NSLog(@"Headers: %@", request.requestHeaders);
NSLog(@"URL: %@", url.absoluteString);
[request setDelegate:self];
[request startAsynchronous];

Which is returning:

Error: Authentication needed

Does anybody have any ideas on this? Successfully authenticated using ASIHTTPRequest?


Solution

  • I successfully use:

    request.shouldPresentCredentialsBeforeChallenge = YES;
    [request addBasicAuthenticationHeaderWithUsername:@"myUser"
                                          andPassword:@"myPass"];
    

    I do not use setAuthenticationScheme for my basic authentication.