user3684980
user3684980

Reputation: 283

Authentication Issue with REST call for iOS

I am currently trying to make a REST call from an iOS device. My code is below

 NSString *restCallString = [NSString stringWithFormat:@"MyURL"];
NSURL *url = [NSURL URLWithString:restCallString];

NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60];
[request setHTTPMethod:@"GET"];
[request addValue:Value1 forHTTPHeaderField:@"Header1"];
[request addValue:Value2 forHTTPHeaderField:@"Header2"];
[request setURL:[NSURL URLWithString:restCallString]];

@try{
      _currentConnection = [[NSURLConnection alloc]   initWithRequest:request delegate:self];
}
@catch(NSError *e){
    NSLog(@"%@", e.description);
}

Whenever this is called, I get the following error: Authentication credentials were not provided. However, what confuses me is that if I send an identical GET request via a HTTP web console, it works perfectly. In other words, using the same URL and the same 2 header-value pairs, I get a valid response on a web console, and see no authentication errors. What could be causing this?

Upvotes: 0

Views: 637

Answers (2)

Carlton Gibson
Carlton Gibson

Reputation: 7386

if I send an identical GET request via a HTTP web console, it works perfectly

I suspect your web console is leveraging SessionAuthentication — i.e. If you're already logged in to your site in your browser the API will authenticate you based on your session cookie.

Django Rest Framework provides various authentication methods and there are third-party options too. The simplest to get going is probably the provided Token Auth method.

Make sure this is enabled. Create a token in the admin (or via the provided view) and make sure you've set the Authorization header. It needs to look like this:

Authorization: Token 9944b09199c62bcf9418ad846dd0e4bbdfc6ee4b

So your Objective-C will go something like:

  [request addValue:[NSString stringWithFormat:@"Token %@", yourToken]
 forHTTPHeaderField:@"Authorization"];

Hopefully that gets you started.

Upvotes: 1

Julian F. Weinert
Julian F. Weinert

Reputation: 7560

You are setting the HTTP headers. This won't work, because the HTTP header is not contained in $_GET or $_POST because they're are not content, but description of the content expected.

Try this instead:

NSURL *url = [NSURL URLWithString:[restCallString stringByAppendingFormat:@"?Header1=%@&Header2=%@", Value1, Value2]];

Of cause you have to be aware that the URL is RFC 1738 compliant.

Upvotes: 1

Related Questions