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

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.

Related

I'm getting header info for a file that doesn't exist?

I'm using code that I got from a tutorial for finding the "Date Modified" info of a file on a server. It goes as follows...
// create a HTTP request to get the file information from the web server
NSMutableURLRequest* request = [NSMutableURLRequest requestWithURL:remoteFileURL];
[request setHTTPMethod:#"HEAD"];
NSHTTPURLResponse* response;
[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:nil];
// get the last modified info from the HTTP header
NSString* httpLastModified = nil;
if ([response respondsToSelector:#selector(allHeaderFields)]) {
httpLastModified = [[response allHeaderFields] objectForKey:#"Last-Modified"];
}
And, for the most part, it works! Wa-hoo.
Except, for a few files, it seems to be returning outdated information. In fact, for at least one, it's returning a date (Fri, 24 Apr 2015 04:32:55 GMT) for a file that doesn't even exist anymore. I deleted it from the server, but it's still returning that value every time I run my app, as if the file still existed.
I've checked and re-checked that the remoteFileURL is pointing to the right URL, and I've confirmed that the file doesn't exist on the server anymore. And, like I said, for most files it works perfectly, so obviously the system isn't entirely broken.
This is my first experience with NSMutableURLRequest and NSHTTPURLResponse and getting file headers and such. Is there something I don't know, that would explain this? Could there be a cache or something that needs to be cleared?
And ideally, what can I do to ensure that the proper info is being received by my app?
Thanks in advance!
Posting my comment as an answer
This type of thing happends because of caching mechanism of NSURL.
Try to add below line to remove all cached data.
[[NSURLCache sharedURLCache] removeAllCachedResponses];
If you want to ignore caching for particulate request try below code
NSURL *url = [NSURL URLWithString:aStrFinalURL];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setCachePolicy:NSURLRequestReloadIgnoringLocalCacheData];

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?
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.

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

What is the easiest way to make an HTTP GET request with IOS 5?

I am trying to send a suggestion from my app to a php file on my web server, I have tested the php script in my browser which sends an email to the user and stores the suggestion in my database, which all works fine.. And when running the following script I get a successful connection via IOS however i do not receive the results in my database..
NSString *post = [NSString stringWithFormat:#"http://blahblah.com/suggest.php?s=%#&n=%#&e=%#", suggestion, name, email];
// Create the request.
NSURLRequest *theRequest=[NSURLRequest requestWithURL:[NSURL URLWithString:post]
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:60.0];
// create the connection with the request
// and start loading the data
NSURLConnection *theConnection=[[NSURLConnection alloc] initWithRequest:theRequest delegate:self];
if (theConnection) {
NSLog(#"Connection establisted successfully");
} else {
NSLog(#"Connection failed.");
}
I have checked all the strings and encoded all spaces with %20 etc.. Can anyone see any glaringly obvious reason why my script won't work?
What is the easiest way to make a HTTP request from my app without opening safari?
You problem is that you're creating the connection, but are not sending the actual "connect" request. Instead of
NSURLConnection *theConnection=[[NSURLConnection alloc] initWithRequest:theRequest delegate:self];
try using this piece of code:
NSURLResponse* response = nil;
NSData* data = [NSURLConnection sendSynchronousRequest:urlRequest returningResponse:&response error:nil]
This is quick and dirty solution, but keep in mind that while this connection is in progress, your UI thread will appear to be frozen. The way around it is to use asynchronous connection method, which is a bit more complicated than the above. Search web for NSURLConnection send asynchronous request - the answer is there.

Resources