I am trying to send an OAuth access token in an HTTP header via NSURLConnection but it doesn't seem to be sending the header because the API keeps giving me an error saying that "must provide authorization token".
This is the code that I am using:
NSURL *aUrl = [NSURL URLWithString: @"http://generericfakeapi.com/user/profile"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:aUrl
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:30.0];
[request addValue:[NSString stringWithFormat:@"OAuth %@", token] forHTTPHeaderField:@"Authorization"];
[request setHTTPMethod:@"GET"];
NSError *error = nil;
NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error: &error];
NSDictionary *JSONDictionary = [NSJSONSerialization JSONObjectWithData:returnData options:kNilOptions error:&error];
NSLog(@"Response : %@", JSONDictionary);
And this is an example of the cURL command for the API:
curl 'http://generericfakeapi.com/user/profile' -H 'Authorization: OAuth YourAuthToken'
Is this not what I am essentially doing through NSURLConnection?
Any help would be appreciated.
I had same problem. In my case I changed "http" to "https" and everything works fine
For me it look fine. Are you sure you gave a valid token? Try catch the error like this
My code work well :
hope it helps
@isair's answer is truly a lifesaver.
Just to add on the root cause if you're interested:
NSURLRequest defines a set of reserved HTTP headers. And surprisingly,
Authrorization
is part of it.In @isair's case, it's highly likely that URLs without a trailing slash had triggered such "filtering" behaviour. This maybe an inconsistency in the implementation but we don't have access to the source code to verify that.
In my case, I was writing a React webapp that uses
Authorization
header to authenticate with the backend Django server. The app behaved perfectly on desktop Chrome but always failed to accesslogin-required
APIs on the iPhone (both Safari and Chrome), due to the missingAuthorization
header.The ideal solution is to avoid using
Authorization
at all. But if you're communicating with a backend framework that specifically requires it (e.g. Django Rest Framework's token authentication). @isair's answer can be a good workaround.Change this line:
To:
Apparently iOS drops the Authorization header if there isn't a slash at the end of a URL. This problem literally cost me my sleep for two days.