Search code examples
rubyfacebook-graph-apisinatrafacebook-iframefacebook-page

Fetching signed_request in a Facebook App with Ruby/Sinatra and the Rest-Graph gem


I've built a Facebook app using Sinatra and the Rest-Graph gem. Now I would like to embed the app as an iframe tab in a Facebook Page.

To do that, I need to fetch data from the signed_request sent to my app by Facebook.

The Rest-Graph gem states the following feature on its Github page:

Utility to extract access_token and check sig in cookies/signed_request

I couldn't find any documentation on how to use this "utility". Can you point me to some documentation or even better, give me an example on how this is used with Ruby/Sinatra?


Solution

  • Nearly all of the Graph API libraries that are available deal with signed_request in a similar way. Rest-Graph has a parse_signed_request method (Rest-Graph/lib/core.rb) that you can call in Sinatra.

    I'm using Koala for this with Sinatra, and it works as advertised:

    oauth = Koala::Facebook::OAuth.new(APP_ID, APP_CODE)
    signed_request = oauth.parse_signed_request(params["signed_request"])
    

    You get back a hash of the JSON object that Facebook posts:

    {
    "algorithm"=>"HMAC-SHA256",
    "issued_at"=>1303883452, 
    "user"=> 
    {
    "country"=>"us",
    "locale"=>"en_US"
    },
    "user_id"=>"100002364226618"
    }
    

    rest-graph makes it pretty easy, too. Just tested this in a Sinatra app. Works perfectly:

    rg = RestGraph.new( :app_id => APP_ID, :secret => APP_SECRET)
    parsed_request = rg.parse_signed_request!(params["signed_request"])
    

    Lemme know if that doesn't work for you.