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)







Comments.