iPhone Authentication with Facebook Connect

by Hugh
November 02, 2009

Here at kaChing, we have multiple platforms to access your Virtual Portfolio. Two of those are the iPhone and Facebook. When we released our iPhone app, we wanted Facebook users to easily login using their Facebook credentials.

Facebook provides an iPhone library that handles sessions/authentication. To show a login dialog:

FBSession *session = [FBSession sessionForApplication:myApiKey
getSessionProxy:myURL delegate:self];
FBLoginDialog* dialog = [[[FBLoginDialog alloc] initWithSession:session] autorelease];
[dialog show];

The dialog will send a session:didLogin message to your delegate.

- (void)session:(FBSession*)session didLogin:(FBUID)uid {
// Don't do this!
user = [service getUserByFacebookId:uid];
}

The problem with the code above is you’re exposing a call in your server which returns private data using only the Facebook ID as a parameter. Facebook IDs are public information, it would be too easy to leak private data.

Instead, pass the Facebook ID along with the session key.

- (void)session:(FBSession*)session didLogin:(FBUID)uid {
user = [service getUserByFacebookId:uid withSession:session.sessionKey];
}

Now let your server authenticate with Facebook using the user’s Facebook ID and session key. Return the user’s data if the ID and session key represents a valid, logged-in user.

User getUserByFacebookId(Long uid, String sessionKey) {
FacebookRestClient client = new FacebookRestClient(apiKey, apiSecret, sessionKey);
if (client.users_getLoggedInUser() == uid) {
return getUserByFacebookId(uid);
} else {
// handle unauthenticated access
}
}

That’s it, now your iPhone client can authenticate users with their Facebook credentials.