Apr 7, 2011

Facebook apps OAuth 2.0 authorization

As you know Facebook implemented OAuth 2.0 authorization for the applications. I recommend you to start learning about this method from http://developers.facebook.com/docs/guides/canvas/#auth.
Here, I want to describe authorization process for client-server Facebook Canvas application assuming that server part is written on Java (JSP / Servlets).

When user tries access your app first time he should be redirected to special dialog to authorize your app and allow it to access your facebook user account data. To show this OAuth dialog you need to redirect user here
https://www.facebook.com/dialog/oauth?client_id=YOUR_APP_ID&redirect_uri=YOUR_CANVAS_PAGE

But how to detect if user is not authorize your app yet? We'll use base64url encoded parameter "signed_request" that is passed to you using HTTP POST method.
Please note: You need to enable "OAuth 2.0 for Canvas" parameter in your app settings on "Advanced" tab.

If user authorized your app then signed_request parameter will have user_id, oauth_token and other attributes. So we need to check if any of that attributes is present and redirect the browser to the dialogue otherwise.

Here is JSP page code example:

<head>
<%
    JSONObject signedRequest = FacebookProvider.decodeSignedRequest(request.getParameter("signed_request"));

    if(signedRequest.has("user_id") == false)
    {
%>
  //Redirect to OAuth dialog using javascript
  <script language="JavaScript" type="text/javascript">
   appId = "12345678"; //Change to your own
   appURL = "http://apps.facebook.com/exampleapp/"; //change to your own
   
   top.location.href = "https://www.facebook.com/dialog/oauth?client_id=" +
                     appId  + "&redirect_uri=" + appURL;
  </script>
  </head>

<%
    }
    else
    {
%>
</head>
 // You are athorized!
... here is your html text ...

<%
 }
%>

1 comment:

  1. Thank you! I was looking for a solution like this for my app for weeks!!! You are a life saver!

    ReplyDelete