Facebook Oauth for fetching page token

28 / Apr / 2014 by Mansi Arora 8 comments

OAuth is a secure mechanism to access facebook.

To access facebook in your grails application you need to create a facebook app, go to https://developers.facebook.com, click on Apps dropdown, further click on ‘Create a new App’.

Ensure that you register the URL of you application with the Facebook app you have setup.

Save your apiKey and secretKey provided by Facebook.

We are going to use Scribe java library for Oauth authentication.

Add this to your BuildConfig.groovy for integrating Scribe.


compile 'org.scribe:scribe:1.3.5'

Create a controller, lets call it Demo Controller and define some variables in it.


class DemoController {
     String apiKey = “xxxxxxxxxxxxxxx”
     String secretKey = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
     String baseUrl = "https://graph.facebook.com/";
     String callbackUrl = “/demo/action2” // link to the callback url of your application
     String fbUserToken // we will get value for this later
     String pageToken // we will get value for this later
}

Now create an action using which we will initiate the Oauth flow


def index() {
     OAuthService service = new ServiceBuilder()
             .provider(FacebookApi.class)
             .apiKey(apiKey)
             .apiSecret(secretKey)
             .scope("manage_pages,read_insights")
             .callback(grailsApplication.config.grails.serverURL + callbackUrl)
             .build();
     String authUrl = service.getAuthorizationUrl(null);
     redirect(url: authUrl.toURL())
}

This action will initiate a call to Facebook Oauth and user will be redirected to a facebook login page. Upon successful authentication, the user will be redirected to the callback url of your application as specified by you. (/demo/action2 in this case).

Here you will receieve authorization code in params. Which you can use to generate a short term token.

def action2() {
     OAuthService service = new ServiceBuilder()
                       .provider(FacebookApi.class)
                       .apiKey(apiKey
                       .apiSecret(secretKey)
                       .scope("manage_pages,read_insights")
                       .callback(grailsApplication.config.grails.serverURL + callbackUrl)
                       .build();
     Verifier v = new Verifier(params.code);
     Token accessToken = service.getAccessToken(null, v); // returns short term token for FB User
     fbUserToken = getLongTermUserToken(accessToken.token) // returns long term token for FB User which is valid for 2 months.
     pageToken = getPageToken(longTermToken) // returns the long term token for the facebook page which has no expiry.
}

Now we have a access token, using which we can make calls to facebook on behalf of user, however, this is only a short term token valid for period of about 10 mins. We can get a long term token using :


fbUserToken = getLongTermUserToken(accessToken.token)  // returns long term token for FB User which is valid for 2 months.

String getLongTermUserToken(String accessToken) {
     String url = baseUrl + "oauth/access_token?grant_type=fb_exchange_token&client_id=${apiKey}&client_secret=${apiSecret}&fb_exchange_token=${accessToken}"
     URL longTermUrl=new URL(url)
     String response = longTermUrl.text
     String longTermToken = extractLongTermToken(response)
     if (!longTermToken) {
          throw new Exception("Some good exception while fetching Long term Token")
     }
     return longTermToken
}

String extractLongTermToken(String response) {
      List list = response.tokenize("&")
      String result = ""
      list.each { String s ->
           if (s.startsWith("access_token")) {
           result = s.tokenize("=").last()
        }
     }
     return result
}

Now we have a long term token, which is valid for about 2 months. However to retrieve page information of a page managed by user, we need another token known as page token. To get page token :


String getPageToken(String longTermToken) {
     String url = baseUrl + "me/accounts?access_token=${longTermToken}"
     URL pageTokenUrl=new URL(url)
     String dataString = pageTokenUrl.text
     JSONObject data = JSON.parse(dataString)
     Map response = data as Map
     String pageToken = extractPageToken(response)
     if (!pageToken) {
          throw new Exception("Some good exception while fetching Page Token")
     }
     return pageToken
}

String extractPageToken(Map response) {
     String pageToken = ''
     response.data.each {
         if (it.id == pageId) {
              pageToken = it.access_token
         }
     }
     return pageToken
}

Notice that we are using long term access token to get the page token. A page token fetched using long term access token has no expiry date. Now we can use this page token to fetch information for the page like page insights etc.

Hope it helps.

Mansi Arora

mansi[at]ntelligrape[dot]com

FOUND THIS USEFUL? SHARE IT

comments (8)

  1. Wiley

    With havin so much content and articles do
    you ever run into any problems of plagorism or copyright violation? My website has
    a lot of unique content I’ve either created myself or outsourced but it seems a lot of it is popping it up all over the web without my authorization. Do you know
    any solutions to help protect against content from being ripped off?

    I’d really appreciate it.

    Reply
  2. private jets small

    I do consider all of the ideas you’ve presented for your post.
    They are very convincing and can definitely work. Nonetheless,
    the posts are very brief for novices. May just you please lengthen them a little
    from next time? Thank you for the post.

    Reply

Leave a comment -