views:

422

answers:

3

for facebook fbml apps facebook is sending in a signed_request parameter explained here

http://developers.facebook.com/docs/authentication/canvas

they have given the php version of decoding this signed request:

http://pastie.org/1054154

how to do the same in python?

i tried base64 module but i am getting Incorrect padding error:

>>> base64.urlsafe_b64decode("eyJhbGdvcml0aG0iOiJITUFDLVNIQTI1NiIsImV4cGlyZXMiOjEyNzk3NDYwMDAsIm9hdXRoX3Rva2VuIjoiMjk1NjY2Njk1MDY0fDIuRXpwem5IRVhZWkJVZmhGQ2l4ZzYzUV9fLjM2MDAuMTI3OTc0NjAwMC0xMDAwMDA0ODMyNzI5MjN8LXJ6U1pnRVBJTktaYnJnX1VNUUNhRzlNdEY4LiIsInVzZXJfaWQiOiIxMDAwMDA0ODMyNzI5MjMifQ")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/base64.py", line 112, in urlsafe_b64decode
    return b64decode(s, '-_')
  File "/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/base64.py", line 76, in b64decode
    raise TypeError(msg)
TypeError: Incorrect padding
+1  A: 

Check out the base64 module.

Zonda333
+2  A: 

Apparently you missed the last two characters when copying the original base64-encoded string. Suffix the input string with two is-equal (=) signs and it will be decoded correctly.

Geert
Geert, thanks for this. but that is exactly the code that i got from facebook and it did not have = at the end. is this expected?
kevin
This is not to be expected I would say.However, you can verify the length of the base64 input by checking the length of it: the length must always be a multiple of 4 bytes (this is actually the reason why the decoder threw an error). If it's not, you can add is-equal signs until it is and then the string will be decoded correctly.
Geert
@Geert: Seems `=` padding is not always required in all variants: http://en.wikipedia.org/wiki/Base64
Nas Banov
PS. seems like the python base64url implementation is *broken* - if i read wiki correct, string does not have to be padded for base64url!
Nas Banov
Geert
+4  A: 

I have shared a code snippet for parsing signed_request parameter in a python based facebook canvas application at http://sunilarora.org/parsing-signedrequest-parameter-in-python-bas

sunil
works good, nice one!
Anentropic