To download a small amount of data from a URL it’s very convenient to use:
NSData *downloadData = [NSData dataWithContentsOfURL:url];
To get data from a URL that requires authentication there several classes that specifically deal with this, e.g. NSURLAuthenticationChallengeSender and NSURLCredential, which require that you use NSURLConnection instead.
NSURLConnection has several other advantages such as asynchronous downloading, but if you just want a one-liner, you can still use NSData dataWithContentsOfURL with basic authentication using the following method.
Normally the URL that you pass to dataWithContentsOfURL looks something like https://www.mysite.com/getmydata
You can add a username and password directly in the URL like this https://username:password@www.mysite.com/getmydata and this type of URL works just fine with NSData dataWithContentsOfURL.
Security Implications
- When you include the username and password in the URL, they may be stored in the web server’s log file.
- If you don’t use SSL, the username and password are sent in clear text.
- Don’t store the URL including the username and password in a property file or plist. These files can easily be viewed by someone looking inside your app bundle.
- Don’t store the credentials like this: NSString *credentials = @”user:password@”; This string is very easy to find in the executable file. If your security requirements are low then you can apply some mild obfuscation: NSString *credentials = [NSString stringWithFormat:@”%c%s%@%c%c%s%@”, ‘u’, “ser:”, @”pas”, ‘s’, ‘w’, “ord”, @”@”]; If you have real security requirements, use real encryption.
February 8th, 2009 at 13:52
Hi, good article!
Just wondering if you were planning to go in depth on this subject of user authentication. Im using the NSCredential and it’d be nice to see a complete tutorial on how to do what you say “obfuscation: NSString *credentials = [NSString stringWithFormat:@”%c%s%@%c%c%s%@”, ‘u’, “ser:”, @”pas”, ’s’, ‘w’, “ord”, @”@”]; If you have real security requirements, use real encryption.” etc. As well as the whole user log in process.
Thanks
February 8th, 2009 at 18:22
@Matt: Thanks for the feedback! Security is something that is near to my heart, so I wouldn’t rule out a follow-up article.
March 9th, 2009 at 05:22
A simple way to download data from a password protected web page…
You’ve been kicked (a good thing) – Trackback from iPhoneKicks.com – iPhone SDK links, community driven…
March 18th, 2009 at 23:49
i m trying to read a text file from specified url and i want to store it in string.
i have tried above solution.but it not working.
plz help
March 19th, 2009 at 06:40
@sanket: It’s difficult to diagnose a problem remotely when the description of the problem is “not working”.