I am working with the Facebook API and Ruby on Rails and I'm trying to parse the JSON that comes back. The problem I'm running into is that Facebook base64URL encodes their data. There is no built-in base64URL decode for Ruby.
For the difference between a base64 encoded and base64URL encoded, see wikipedia.
How do I decode this using Ruby/Rails?
Edit:
Because some people have difficulty reading - base64 URL is DIFFERENT than base64
Dmitry's answer is correct. It accounts for the '=' sign padding that must occur before string decode. I kept getting malformed JSON and finally discovered that it was due to the padding. Read more about base64_url_decode for Facebook signed_request.
Here's the simplified method I used:
def base64_url_decode(str)
str += '=' * (4 - str.length.modulo(4))
Base64.decode64(str.tr('-_','+/'))
end
Googling for "base64 for URL ruby" and choosing the first result lead me to the answer
cipher_token = encoded_token.tr('-_','+/').unpack('m')[0]
The details of the cipher_token aren't important save that it can contain any byte values.
You could then, of course, make a helper to base64UrlDecode( data )
.
What's happening is that it takes the encoded_token
and replaces all the -
and _
characters with +
and /
, respectively. Then, it decodes the base64-encoded data with unpack('m')
and returns the first element in the returned array: Your decoded data.
For base64URL-encoded string s
...
s.tr('+/', '-_').unpack('m')[0]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With