Integrating Facebook from a Grails app

Last weeks I was trying to integrate some Facebook API calls from a Grails app and dive into Facebook Graph API developer documentation. After some research on Java/Groovy accelerators about implementing Facebook OAuth authentication protocol, I found myself in a position that I had to realize my own solution … That’s a very weird situation for me cause I’m usually lazy and very reluctant as reinventing the wheel. However, I came to a very light and elegant solution so I thought I would share it here …

My use case

The use case I have was pretty simple : don’t want to have a Facebook connect style application but want to allow a user to find within my application some of its friends already having an account. This imply that : we should ask user the permission to request its Facebook account and that request should occur on the server side while we may want to do some complex processing in order to display user a consolidated list of potential friends.

By the way, I was implementing this use case for the Trailplans application, a free service for discovering and sharing walks, bike or urban trails through points of interest. See announcement about this feature availability here.

The candidates I look at

First candidate, I obviously look at was Grails Facebook Plugin. However, from what I understand by plugin seems to be client oriented (facebook connect feature) and to rely on the fact that user has already an opened Facebook session in order to made the FacebookGraphService available. Moreover this plugin has a dependency with Grails 1.3.3 and my application is still in version 1.2.2. Bad.

Then, I look at the Facebook Java API available on Google Code. Maybe this project is good enough and does the job, the fact is that the documentation did not give a clue on how to realize Oauth process and to interact with FB on behalf of a registred user that has allow application to do so. Bad.

Last library I look at and I finally choose to pick to implement the requesting part of my use case was restfb, a simple yet powerful Graph API made on Java. Restfb focuses on the important : provide minimal but powerfull APIs with no extra dependencies.

Facebook application first steps

First step when wanting to develop an application integrating with Facebook is to register a new app through their Developper website.

Doing so, you retrieve some capital informations for the rest of your developments : your OAuth client_id and your OAuth client_secret. Naturally, you shoud have provided correct URL and domain information for your application.

In order to store that 2 OAuth informations into your Grails application, I suggest you to use a simple Spring Bean declared into resources.groovy within grails-app/conf/spring directory. Here’s an example :

Grails integration

Here’s now the time to write the Grails integration layer. As you will see here, an important part of this layer (important but ony 5 lines !) is about implementing the authentication flow that is called Server-side flow within Facebook documentation.

And here’s simply the Grails controller code :

import com.restfb.Connection;
import com.restfb.FacebookClient;
import com.restfb.DefaultFacebookClient;
import com.restfb.types.User;
* Controller integrating with Facebook
* @author laurent
class FacebookController {
   def facebookKeys

   def index = {}

   def authent = {
      def redirectURI = createLink(absolute:true, action: 'callback')
      redirect(url: "${facebookKeys.clientCode}&redirect_uri=${redirectURI}")

   def callback = {
      // Request an access token by fetching url with given code.
      def redirectURI = createLink(absolute:true, action: 'callback')
      def rootUrl = "${facebookKeys.clientCode}&client_secret=${facebookKeys.clientSecret}"
      String accessTokenURL = rootUrl + "&redirect_uri=${redirectURI}&code=${params.code.encodeAsURL()}"
      String result = new URL(accessTokenURL).getText()
      // Access token is first key=value pairs value.
      String accessToken = result.tokenize("&")[0].tokenize("=")[1]
      // Use a facebook client to request current logged in user friends.
      FacebookClient fb = new DefaultFacebookClient(accessToken)
      Connection friends = fb.fetchConnection("me/friends", User.class)
      render(view: 'callback', model: [friends:])

The flow goes as follow : when wanting to interact with Facebook, user goes to the authent action that simply redirects it to a Facebook authentication page where our application is identified (client_id) and where redirection goes to our callback action after successfull authent.

The callback action is passed a code request parameter by Facebook. This parameter should be used for later requesting an access_token to a Facebook URL (client_id and client_secret are once again specified to let FB identify our application). Return of this call is a key=value pairs; the first value representing token value. The parsing of result is done with result.tokenize("&")[0].tokenize("=")[1] statement.

Once access_token is acquired, you can simply use it with simple restfb APIs. That’s it : just 5 lines to implement Facebook OAuth process !


5 thoughts on “Integrating Facebook from a Grails app

  1. Thanks for sharing. Your solution seems like good fit to my application requirement, I will test it out.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s