Monday, January 17, 2011

The Facebook login & logout flow for Android platform

Recently I am working on a mobile application project using the FaceBook API. I never touched Facebook API before, for me the first thing is to understand how the Facebook login/logout works on the mobile apps, so I spent some time on figure out how does it work on the Android platform.

I just summarized the login and logout flow based on the Facebook android SDK source code and its sample app log output.

First you need to register your application and get your application ID from the facebook website.

Login Flow

Request format:
https://m.facebook.com/dialog/oauth?client_id=xxxx&redirect_uri=fbconnect://success&display=touch&type=user_agent
example:
https://m.facebook.com/dialog/oauth?client_id=175729095772478&redirect_uri=fbconnect://success&display=touch&type=user_agent

Here,
client_id is your application id.
display=touch means the device smart phone (android or iphone)

response:
fbconnect://success/#access_token=xxxxx&expires_in=xxxxx
example:
fbconnect://success/#access_token=175729095772478%7C2.vQIILuM8Bu_9nLKrl4yIew__.3600.1294938000-100000460660639%7Ch9OreeWmU4iUMB47UKwl20H64Gg&expires_in=4593

You need to launch a browser inside your app to send the login the request, browser will display a login dialog let input the facebook account and password, then if login successful, the browser will return the redirected URL(fbconnect://success) with the access_token and expired value.

To retrieve these values, you need to intercept the redirected URL: check if it starts with fbconnect://success, then parse the response, get the access_token and expire value.


Logout Flow
format:
https://api.facebook.com/restserver.php?access_token=[your access_token]
                                       &method=auth.expireSession&format=json
example:
https://api.facebook.com/restserver.php?access_token=175729095772478%7C2.mJlReipn5lu6jEJrKU2D6w__.3600.1295024400-100000460660639%7CE7f8hi-RkJtxOoJmGTyaWFgXHfI&method=auth.expireSession&format=json

If logout successfully, the response will return text "true",
otherwise it will return a JSON text contains the detailed error message.