While working with the Facebook API and Ruby on Rails and I was trying to parse the JSON that comes back. The problem i was facing was that Facebook base64URL encodes their data. There is no built-in base64URL decode for Ruby(1.8.7). For ruby 1.9.2 they've included method in base64 module.
While decoding with base64, I kept getting malformed JSON and finally discovered that it was due to the padding.
Fix for this consists of three steps:-
1) Count the length of the payload and see if it’s divisible by 4 (with the modulus operator). If the remainder is 2 then we add 2 equal signs. If the remainder is 3 then we add 1 equal sign to the end of the payload(part after dot operator in signed_request).
2) Replace the character ‘-’ with ‘+’, and ‘_’ with ‘/’
Combining these steps into a method. I created a helper method.
Hope it helps someone else trying to base64 decode Facebook’s signed_request in Ruby on Rails.
While decoding with base64, I kept getting malformed JSON and finally discovered that it was due to the padding.
Fix for this consists of three steps:-
1) Count the length of the payload and see if it’s divisible by 4 (with the modulus operator). If the remainder is 2 then we add 2 equal signs. If the remainder is 3 then we add 1 equal sign to the end of the payload(part after dot operator in signed_request).
2) Replace the character ‘-’ with ‘+’, and ‘_’ with ‘/’
Combining these steps into a method. I created a helper method.
def base64_url_decode(str)
str += '=' * (4 - str.length.modulo(4))
Base64.decode64(str.tr('-_','+/'))
end
Hope it helps someone else trying to base64 decode Facebook’s signed_request in Ruby on Rails.
No comments:
Post a Comment