By continuing to use the site, you agree to the use of cookies.

Continue More information

Decoding and Accessing The signed_request Parameter in Rails

02 March 2011COMMENTS

For a recent Rails project I needed to decode and parse the Facebook signed_request, to be used within the context of a facebook application.

A signed_request is passed to apps on Facebook.com when they are loaded into the Facebook environment (although there are other circumstances when the parameter can be utilised).

The signed request parameter comes in the form of SHA-256 signature string and a Base64URL encoded JSON object. Ruby doesn’t have Base64URL decoding support so we are required to write two small helpers. The first replaces - with + and _ with /.

After this the string can be decoded with Base64. The second decodes the data, splitting the signature from the payload, which are seperated by a period.


def base64_url_decode str
encoded_str = str.gsub('-','+').gsub('_','/')
encoded_str += '=' while !(encoded_str.size % 4).zero?
Base64.decode64(encoded_str)
end

def decode_data str
encoded_sig, payload = str.split('.')
data = ActiveSupport::JSON.decode base64_url_decode(payload)
end

We’re now able to access the contents of the payload.

signed_request = params[:signed_request]

@signed_request = decode_data(signed_request)

Share.

  • Twitter
  • Facebook
  • Google+
  • LinkedIn
  • Delicious
  • StumbleUpon
  • MySpace
  • Digg
  • Netvibes
  • Tumblr
  • Bebo

Author.

James Walton
James Walton (Junior Developer)

Comments.

nelson posted 7th March 2011
nice post. a quick copy and paste of the code and it worked brilliantly. Thank you!
recurser posted 28th November 2011
Perfect, much appreciated!!
Tjerk posted 30th November 2012
I have the @signed_request instance and its filled with all this data I got, but how do I approach the data inside this instance?

for example I want to make a new user with this data.

User.name = @signed_request[:name]
User.save

I've tried in many ways but I can't seem to find the right one.

Add new comment.

You are commenting as a guest (guest comments will be moderated before being published).

Optional: Login below:
*Required fields

Labs are the views and thoughts of staff at Acknowledgement focused around making and doing digital things!

VISIT OUR MAIN SITE
  1. Privacy Policy
  2. T&Cs of business
  3. Website T&Cs
© Acknowledgement 2013. All rights reserved.