Facebook OAuth 2.0 for Canvas App Explained

Facebook is getting better in providing OAuth 2.0 support for its canvas app, that is apps on facebook.com. But one thing that drives people nuts is the documentation. A lot of people getting stuck while trying to adopt the new OAuth authentication method and the Graph API because lack of proper documentation for developers.

This post will explain how simple actually getting OAuth to work with canvas app (both FBML and iFrame). There are two references you need:

  1. http://developers.facebook.com/docs/authentication/
  2. http://developers.facebook.com/docs/authentication/canvas

Authenticating User

The docs on authentication explains that you need to perform two steps to obtain the access_token that is:

  1. Redirect the user to https://graph.facebook.com/oauth/authorize  with your client_id and the URL the user should be redirected back to after the authorization process (redirect_uri)
  2. Exchange it for an access token by fetching https://graph.facebook.com/oauth/access_token. Pass the exact same redirect_uri as in the previous step (1).

For canvas app, it is much more simpler. You do not need to perform step 2. What you need is just step 1, the authorization process. See code below:

After this process, you can parse the signed_request (see below) to get the access_token.

The signed_request

All canvas apps will have this signed_request parameter attached to the callback URL that contains the user_id, oauth_token, expires and profile_id. You need to parse the signed_request to get these info. Example codes can be found here: PHP, .NET (C#), Python, Java.

So, now you are able to parse and get those info, and yes you will get the oauth_token directly. If you get nothing returned (no user_id, oauth_token, etc), don’t freak out. This means the user has not authorize your app yet. So, just perform the authorization process above and you are good to go!

The Good and Bad

The good thing is, it much more simpler — you no longer need to request for a new access_code/access_token when it expires, back and forth. Just parse the signed_request to get the access_token (oauth_token).

The bad thing is, the authorization process doesn’t work well with iFrame-based canvas app. You will get a Facebook inside Facebook effect, that is a Facebook page loaded inside the Facebook frame.

The Workaround for iFrame

The current workaround is using Javascript to load the authorization URL on top:

This will solve part of the problem. After the user authorized your app, Facebook will redirect back to your site specified by the redirect_uri. You will get the problem again (you will see a Facebook logo with a ‘Go to Facebook.com’ link). After much hack-around, I found out that by adding type=’user_agent’ and display=’page’ to the authorization URL, the problem is fixed. See the modified URL below:

There you go.