Authentication Issue with REST call for iOS - 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?

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.

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.

Related

Why do i get authenticationchallenge with NSURLRequest when switching to HTTPS?

I've used NSMutableURLRequest for a long time to connect to my server.
In order to avoid double roadtrips, i set the usr/pwd right away in the header, like this:
NSMutableURLRequest *request = [NSMutableURLRequest
requestWithURL:[NSURL URLWithString:url]
cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:HTTP_REQUEST_TIMEOUT];
NSString *authStr = [NSString stringWithFormat:#"%#:%#", inUsr, inPwd];
NSString *authValue = [NSString stringWithFormat:#"Basic %#", [[authStr dataUsingEncoding:NSISOLatin1StringEncoding] base64EncodedStringWithOptions:0]];
[request setValue:authValue forHTTPHeaderField:#"Authorization"];
This has worked fine, the "willSendRequestForAuthenticationChallenge" is never called unless there is some error, so that method has always looked like:
- (void)connection:(NSURLConnection *)connection willSendRequestForAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge {
NSDictionary *errorInfo = ((NSHTTPURLResponse *) challenge.failureResponse).allHeaderFields;
NSError *error; = [NSError errorWithDomain:#"httprequesthandler" code:WRONG_CREDENTIALS userInfo:errorInfo];
[delegate finishedWithErrors:error];
Now however, i'm using the same URL's as always, only "https" instead of "http", and suddenly this method is called every time.
I want my request to work as per normal, i.e. populate basic header and only one request to the server.
I'm not sure what i'm missing, so pointers would be much appreciated!
Using https as your scheme (or protocol) requests the connection be made securely, both by encrypting the data that is transferred as well as offering some information to you about the authenticity of the server you are connecting to.
The delegate method being invoked here (connection:willSendRequestForAuthenticationChallenge:), is not related to you authenticating yourself with the server, but the server authenticating itself with you. If you dig into the challenge object (NSURLAuthenticationChallenge), you can find the credentials the server is offering to let you know that it is the server you were actually trying to connect to, instead of an impostor.
Normally you don't need to use this method unless you want to validate the server in a way that goes beyond what the OS is doing for already.

Set the header in ASIHTTPRequest

I'm using ASIHTTPRequest to access a web based API and need to set a header for App authentication. Note that this is not a server level authentication it is at API level. I've tried every thing I could find and most of the answers on the web as well as the ones here at www.stackoverflow.com tell me to use something like:
[request addRequestHeader:#"username" value:#"asdf"];
This does not work for me. The guy who built the API I'm using told me that I need to set the header as:
Authorization: TRUEREST username=PersonName&password=pass&apikey=dfiu6aewruif3Bismillah4Rah3anArahimiImi22MyDad
So I tried the following:
NSURL *url = [NSURL URLWithString:#"http://ifish-uk.co.uk/rest_users/login.json"];
ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
[request addRequestHeader:#"username" value:#"MyUser"];
[request addRequestHeader:#"password" value:#"MyPass"];
[request addRequestHeader:#"apikey" value:#"dfiu6aewruif3Bismillah4Rah3anArahimiImi22MyDad"];
But it didn't work... I even tried setting the Request type to GET because the developer told me I should do this:
[request setRequestMethod:#"GET"];
This didn't work... The API developer told me he is made this module as follow:
POST /rest_catches/add.json HTTP/1.1
Host: ifish-uk.co.uk
Authorization: TRUEREST username=MyUser&password=MyPass&apikey=dfiu6aewruif3Bismillah4Rah3anArahimiImi22MyDad
Cache-Control: no-cache
any help would be greatly appreciated.
You should add only one header is Authorization no need to add separate headers for each field (use, pass, etc).
Fill it with your specific values and send.
[request addRequestHeader:#"Authorization" value:#"TRUEREST username=PersonName&password=pass&apikey=dfiu6aewruif3Bismillah4Rah3anArahimiImi22MyDad"];
Did you try adding:
[request setRequestMethod:#"POST"];
?

NSURLConnection Authorization Header not Working

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.
Change this line:
NSURL *aUrl = [NSURL URLWithString: #"http://generericfakeapi.com/user/profile"];
To:
NSURL *aUrl = [NSURL URLWithString: #"http://generericfakeapi.com/user/profile/"];
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.
#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.
The URL Loading System handles various aspects of the HTTP protocol for you (HTTP 1.1 persistent connections, proxies, authentication, and so on). As part of this support, the URL Loading System takes responsibility for certain HTTP headers:
Content-Length
Authorization
Connection
Host
Proxy-Authenticate
Proxy-Authorization
WWW-Authenticate
If you set a value for one of these reserved headers, the system may ignore the value you set, or overwrite it with its own value, or simply not send it. Moreover, the exact behavior may change over time. To avoid confusing problems like this, do not set these headers directly.
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 access login-required APIs on the iPhone (both Safari and Chrome), due to the missing Authorization 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.
For me it look fine. Are you sure you gave a valid token?
Try catch the error like this
if (error) {
NSLog(#"error : %#", error.description);
}
My code work well :
NSURL *jsonURL = [NSURL URLWithString:[NSString stringWithFormat:#"http://....ID=%i", cellID]];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:jsonURL cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:120.0];
[request setValue:#"Basic ...." forHTTPHeaderField:#"Authorization"];
NSURLResponse *response;
NSError * error = nil;
NSData *POSTReply = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
hope it helps
I had same problem. In my case I changed "http" to "https" and everything works fine

Disqus Password Credentials OAuth

I'm trying to authenticate a user in my iOS app but all I get is a 400 error.
According to the documentation, "this type of flow is restricted to approved applications only, so you must request access first".
So how do I approve my application to be able to accomplish this flow?
Part of my request:
NSURL *url = [NSURL URLWithString:#"https://disqus.com/api/oauth/2.0/access_token/"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:WS_TIMEOUT];
NSString *strAuth = [NSString stringWithFormat:#"%#:%#", username, password];
NSString *strAuthBase64 = [[strAuth dataUsingEncoding:NSUTF8StringEncoding] base64EncodedString];
NSString *postString = [NSString stringWithFormat#"grant_type=password&client_secret=%#&client_id=%#&scope=read,write", DISQUS_SECRET, DISQUS_KEY];
[request addValue:[NSString stringWithFormat:#"Basic %#", strAuthBase64] forHTTPHeaderField:#"Authorization"];
[request setHTTPMethod:#"POST"];
[request setHTTPBody:[postString dataUsingEncoding:NSUTF8StringEncoding]];
Thanks in advance.
This is something we'd have to enable for your application from our end. However, I'd instead recommend hosting a page to handle the authentication with the standard server-side flow. You can then pull the access token and other variables from the page into your application after the user has authorized.
The reason is so you don't have to deal with form validation, error messaging, and can take advantage of our updates to the form without touching your code.
Some server-side OAuth examples in PHP and Python can be found on this page: https://github.com/disqus/DISQUS-API-Recipes/tree/master/oauth
Try this library which solves Disqus authorization issue in a slick manner. Really nice solution https://github.com/moqod/disqus-ios

iOS - REST Client works fine while NSURLRequest returns NULL

I'm trying to download a file from a cloud via a GET HTTP request, and in my REST Client (Postman for Chrome) I get the results as expected, but when I pass the request in iOS, I get a NULL response. What could be the problem?
In my REST Client, I pass the URL as http://myserver.com/api/download.json?filepath=/&fileid=document:1pLNAbof_dbXGn43GtMNafABMAr_peTToh6wEkXlab7U&filename=My Info.doc with a header field for a authorization key, and it works perfectly fine.
While in iOS, if I do such a thing:
[request setURL:[NSURL URLWithString:URLString]]; // I tried even to hardcode the
// URLString to be one of the
// working URLs from the Postman
// Client, doesn't work as well.
[request setHTTPMethod:#"GET"];
NSData* response = [NSURLConnection sendSynchronousRequest:request
returningResponse:&urlResponseList
error:&requestErrorList];
response is null, and I get a status code 500.
Anyone know how to make this work? Thanks.
it looks like your URL has a space in it, you'll need to escape that before sending the string to NSURL.
it would also be helpful to know what the full error from your server is if this doesn't work. what does requestErrorList contain?
but if the only problem is the non-escaped characters something like this should work.
NSString *encodedString = [URLString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
[request setURL:[NSURL URLWithString:encodedString];
An HTTP status code 500 occurs when the webservice is not able to handle your request. An internal error occured.
Try to add some more details to your request.
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];

Resources