Rss Feed Tweeter button Facebook button Technorati button Reddit button Linkedin button Webonews button Delicious button Digg button Flickr button Stumbleupon button Newsvine button

A Waage Blog

Ruby, Rails, Life

Archive for the ‘Facebook API’ Category

Facebook base64 url decode for signed_request

with 9 comments

I ran into a problem as I was trying to decode and parse the Facebook signed_request for their new Registration plugin (http://developers.facebook.com/docs/plugins/registration).

Folowing the PHP example, I attempted to decode and read the signed_request returned by Facebook. Unfortunately, it seemed like the decoded JSON returned was malformed! It was missing the end hash character “}”. This may not happen in all cases, but the reason is due to the padding in Base64 encoding (See Base64 for URLs in Wikipedia).

To account for the padding in Base64, I used the following helper method to do the base64_url_decode. Hope it helps someone else trying to base64 decode Facebook’s signed_request in Ruby on Rails!:

 def base64_url_decode(str)
   str += '=' * (4 - str.length.modulo(4))
   Base64.decode64(str.tr('-_','+/'))
 end

Notice there’s two things that must happen before decoding the string:

  1. Pad the encoded string with “=”
  2. Replace the character ‘-’ with ‘+’, and ‘_’ with ‘/’

I wish Facebook mentioned this clearly on their API !

Written by Andrew Waage

February 8th, 2011 at 1:27 pm