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

Facebook base64 url decode for signed_request

with 6 comments

I ran into a problem as I was trying to decode and parse the Facebook signed_request for their new Registration plugin (

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))

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

6 Responses to 'Facebook base64 url decode for signed_request'

Subscribe to comments with RSS or TrackBack to 'Facebook base64 url decode for signed_request'.

  1. Thanks, this helped up debug and solve this nasty problem. I agree with you. Facebook should be more clear about this. And thanks again.


    16 Feb 11 at 8:18 pm

  2. Wow. That only took me a complete day of wasted time until I found your post. Many, many THANKS! Re-inserting hair follicles now.


    13 Apr 11 at 7:29 am

  3. I am not techie– How do i pad encoded string with “=” when i have bulk of URLs to decode?


    25 Aug 11 at 1:39 am

  4. Thanks. Just what I needed to make it work.


    8 Dec 11 at 5:23 am

  5. @chris – You can run all your URLs through the method defined above in the post. This handles decoding properly, including padding the string with “=” -Andrew

    Andrew Waage

    8 Dec 11 at 9:42 am

  6. I think add line it work.
    def decode_data str
    encoded_sig, payload = str.split(’.')
    data = ActiveSupport::JSON.decode base64_url_decode(payload)

    referent :


    14 Mar 12 at 4:03 am

Leave a Reply