iPhone: HTTP Authentication - Basic Auth vs HTTP Sessions

So I have a service that I want to allow users to reach via the iPhone. Now on the website, obviously, sessions are in play. How does that translate to the iPhone. After reading around a bit, my thought is that it would be via HTTP Basic Auth. In that, I use NSURLConnection and NSURLCredential, make my request to the URL set for basic auth. The auth handler would then get the username/password and validate it against the current users DB and return accordingly effectively giving the iPhone application the ability to make request after request against another basic auth required URL to get it's data.

Is this the correct methodology?

So the main thing I need to enable is an http auth handler on my server to receive iPhone requests. In other words, in place of sessions (browser) we are to use http basic auth. Correct?

MacBook Pro 2.5ghz, Mac OS X (10.5.3), 4gb RAM

Posted on Sep 27, 2008 4:39 PM

Reply
11 replies

Sep 27, 2008 5:26 PM in response to orangekay

Oh ya, typically if this were purely web based, I would store the fact the user has logged in within the session. Thus closing their browser, or upon logout, the session is destroyed, the user has to log back in again.

I looks like I could use NSHTTPCookie and set isSessionOnly:

My main question was more of the best practice (should have phrased it better). So the application will be on the phone.

1) I could, send the users, login/password once the application starts, if it's valid, create an NSHTTPCookie, that the server would then read to see if it should allow various requests to the RESTful services

2) Go the NSURLConnection and NSURLCredential route on startup, and access to the RESTful services would be behind Basic HTTP Auth. The server would not have to check for the presence of the cookie each time, as one authentication provides access to all of the available services via the initial authentication request on startup.

Just curious which is the best way to go for an iPhone App that will rely on external data providers.

Sep 28, 2008 12:33 PM in response to logix812

Yet another way of looking at it:

Looking for any examples that would allow me to get the Cookies set on the server from a NSURLRequest.

Basically, I need to have a user logged in, so they can get various data related to their account.

So like any other web based auth system, the user would submit their name/pass and, if valid, a cookie would be set (session or otherwise) that tells the system the user is indeed logged in.

If this were PHP it would be something like:

if(!$_SESSION['loggedInToken']){
header('Location: http://www.example.com/login');
}


or
$_COOKIE could be used..

in any case, the idea is the same, I want the iPhone to send the user credentials to the server for authentication, and I want the iPhone to be able to get the Cookie that is set, as well as send the Cookie when it makes additional requests to the server.

Can anyone point me in the right direction. I am positive I need some combination of :

NSURLRequest/NSURLMutableRequest
NSURLConnection
NSHTTPCookie

The Docs on NSHTTPCookie, to me anyway, seem unclear.

Sep 28, 2008 4:04 PM in response to logix812

Ok.. I got it... Here is the round trip on using NSHTTPCookie

The following makes a request to the server, the server sets some cookies and the response is returned, the cookies are stored in NSHTTPCookieStorage and retrieved, and sent back to the server. The server then acknowledges it received the cookies. On the server side I am using Python/mod_python, but it could just as easily be done with a server side language of your choosing, just need to know how to set cookies with it.

OBJECTIVE-C

NSHTTPURLResponse * response;
NSError * error;
NSMutableURLRequest * request;
request = [[[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:@"http://temp/gomh/authenticate.py?setCookie=1"]
cachePolicy:NSURLRequestReloadIgnoringCacheData
timeoutInterval:60] autorelease];

[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSLog(@"RESPONSE HEADERS: %@", [response allHeaderFields]);

// If you want to get all of the cookies:
NSArray * all = [NSHTTPCookie cookiesWithResponseHeaderFields:[response allHeaderFields] forURL:[NSURL URLWithString:@"http://temp"]];
NSLog(@"How many Cookies: %d", all.count);
// Store the cookies:
// NSHTTPCookieStorage is a Singleton.
[[NSHTTPCookieStorage sharedHTTPCookieStorage] setCookies:all forURL:[NSURL URLWithString:@"http://temp"] mainDocumentURL:nil];

// Now we can print all of the cookies we have:
for (NSHTTPCookie *cookie in all)
NSLog(@"Name: %@ : Value: %@, Expires: %@", cookie.name, cookie.value, cookie.expiresDate);


// Now lets go back the other way. We want the server to know we have some cookies available:
// this availableCookies array is going to be the same as the 'all' array above. We could
// have just used the 'all' array, but this shows you how to get the cookies back from the singleton.
NSArray * availableCookies = [[NSHTTPCookieStorage sharedHTTPCookieStorage] cookiesForURL:[NSURL URLWithString:@"http://temp"]];
NSDictionary * headers = [NSHTTPCookie requestHeaderFieldsWithCookies:availableCookies];

// we are just recycling the original request
[request setAllHTTPHeaderFields:headers];

request.URL = [NSURL URLWithString:@"http://temp/gomh/authenticate.py"];
error = nil;
response = nil;

NSData * data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSLog(@"The server saw: %@", [[[NSString alloc] initWithData:data encoding: NSASCIIStringEncoding] autorelease]);


*PYTHON (mod_python)*

import time
from mod_python import apache
from mod_python.util import FieldStorage
from mod_python import Cookie
def handler(req):
data = FieldStorage(req)

if data.has_key('setCookie'):
c = Cookie.Cookie("userid", 1)
c2 = Cookie.Cookie("foo", "bar")
c.expires = time.time() + 86400
c2.expires = time.time() + 86400
Cookie.add_cookie(req, c)
Cookie.add_cookie(req, c2)
else:
cookies = Cookie.get_cookies(req, Cookie.Cookie);
req.write("Available Cookies: %s" % str(cookies))

return apache.OK

Dec 5, 2008 12:47 PM in response to logix812

logix812 wrote:
Ok.. I got it... Here is the round trip on using NSHTTPCookie

The following makes a request to the server, the server sets some cookies and the response is returned, the cookies are stored in NSHTTPCookieStorage and retrieved, and sent back to the server. The server then acknowledges it received the cookies. On the server side I am using Python/mod_python, but it could just as easily be done with a server side language of your choosing, just need to know how to set cookies with it.

OBJECTIVE-C

NSHTTPURLResponse * response;
NSError * error;
NSMutableURLRequest * request;
request = [[[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:@"http://temp/gomh/authenticate.py?setCookie=1"]
cachePolicy:NSURLRequestReloadIgnoringCacheData
timeoutInterval:60] autorelease];
[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSLog(@"RESPONSE HEADERS: %@", [response allHeaderFields]);
// If you want to get all of the cookies:
NSArray * all = [NSHTTPCookie cookiesWithResponseHeaderFields:[response allHeaderFields] forURL:[NSURL URLWithString:@"http://temp"]];
NSLog(@"How many Cookies: %d", all.count);
// Store the cookies:
// NSHTTPCookieStorage is a Singleton.
[[NSHTTPCookieStorage sharedHTTPCookieStorage] setCookies:all forURL:[NSURL URLWithString:@"http://temp"] mainDocumentURL:nil];
// Now we can print all of the cookies we have:
for (NSHTTPCookie *cookie in all)
NSLog(@"Name: %@ : Value: %@, Expires: %@", cookie.name, cookie.value, cookie.expiresDate);
// Now lets go back the other way. We want the server to know we have some cookies available:
// this availableCookies array is going to be the same as the 'all' array above. We could
// have just used the 'all' array, but this shows you how to get the cookies back from the singleton.
NSArray * availableCookies = [[NSHTTPCookieStorage sharedHTTPCookieStorage] cookiesForURL:[NSURL URLWithString:@"http://temp"]];
NSDictionary * headers = [NSHTTPCookie requestHeaderFieldsWithCookies:availableCookies];
// we are just recycling the original request
[request setAllHTTPHeaderFields:headers];
request.URL = [NSURL URLWithString:@"http://temp/gomh/authenticate.py"];
error = nil;
response = nil;
NSData * data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSLog(@"The server saw: %@", [[[NSString alloc] initWithData:data encoding: NSASCIIStringEncoding] autorelease]);


*PYTHON (mod_python)*

import time
from mod_python import apache
from mod_python.util import FieldStorage
from mod_python import Cookie
def handler(req):
data = FieldStorage(req)
if data.has_key('setCookie'):
c = Cookie.Cookie("userid", 1)
c2 = Cookie.Cookie("foo", "bar")
c.expires = time.time() + 86400
c2.expires = time.time() + 86400
Cookie.add_cookie(req, c)
Cookie.add_cookie(req, c2)
else:
cookies = Cookie.get_cookies(req, Cookie.Cookie);
req.write("Available Cookies: %s" % str(cookies))
return apache.OK



In this scenarios, were you controlling the server side login? I'm looking to do something I believe is similar, only I'm trying to login to a 3rd party site. (For example: google.com) So I'm basically trying to allow a user to authenticate for their account, capture the cookie, and then supply the cookie when navigating to another url so the user can parse their data.

thanks!

Mar 10, 2009 7:50 PM in response to logix812

Hi,
I'm trying to create an iPhone native application that integrates and interacts with a Ruby on Rails web application. The iphone client app needs to download data (using NSURLdownload) etc after the user is authenticated.
We want to use the user's web credentials (their username and password from website) to be passed from iPhone native client application.

Can some one please point me to an example or relevant material which shows how user from iphone app can authenticate against Ruby on Rails server.

Thanks in advance,
Navneet

Jul 17, 2009 5:16 PM in response to belsokar

Did you ever manage to figure out what the "best practise" was for this type of authentication? I'm using PHP on my webserver and I'm brand new to iPhone/Obj-C dev so Apple's vague white papers are really not helping me much. Now that 3.0 is out I feel like things might have changed the game some too.

Any ideas?

This thread has been closed by the system or the community team. You may vote for any posts you find helpful, or search the Community for additional answers.

iPhone: HTTP Authentication - Basic Auth vs HTTP Sessions

Welcome to Apple Support Community
A forum where Apple customers help each other with their products. Get started with your Apple Account.