4

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?

Javier
  • 2,491
  • 4
  • 36
  • 57

2 Answers2

7

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.

cmptr
  • 382
  • 1
  • 5
  • Just saw that you edited your code. It now reflects the solution I got from cardinalblue today. Anyway, as you were the first answering my question and I can't take that bounty back: It's yours. :) – Javier May 02 '11 at 20:15
0

I just got a response to this question from "cardinalblue", the developer of the Rest-Graph gem. This little example was exactly what I was looking for:

require 'sinatra'
require 'rest-graph'

app_id = '123'
secret = 'abc'
config = {:app_id => app_id,
          :secret => secret}

post '/' do
  rg = RestGraph.new(config)
  rg.parse_signed_request!(params['signed_request'])
  "#{rg.get('me').inspect.gsub('<', '&lt;')}\n"
end

run Sinatra::Application

Sidenote: In case you're building something similar, please note the post '/' do. Facebook Pages fetch your page using a POST request instead of a GET.

Javier
  • 2,491
  • 4
  • 36
  • 57
  • Yep -- I'm using a POST in my app; guess I assumed that anyone looking to parse signed_request would be doing the same. :) Cheers! – cmptr May 02 '11 at 22:40
  • I guess you're right. I just added that line, because it took me some time to get that, as my app wasn't running inside FB canvas before (that's also why I was looking for this "signed_request" thing ;-)). – Javier May 02 '11 at 22:59
  • FWIW, Facebook also uses signed_request the deauthorize URL. Just something you'll probably want to implement now that you're parsing it successfully. – cmptr May 03 '11 at 17:28