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
To decode an image using Python, we simply use the base64. b64decode(s) function. Python mentions the following regarding this function: Decode the Base64 encoded bytes-like object or ASCII string s and return the decoded bytes.
To decode with base64 you need to use the --decode flag. With encoded string, you can pipe an echo command into base64 as you did to encode it. Using the example encoding shown above, let's decode it back into its original form. Provided your encoding was not corrupted the output should be your original string.
b64decode() in Python. The base64. b4() function in Python decodes strings or byte-like objects encoded in base64 and returns the decoded bytes.
try
s = 'iEPX-SQWIR3p67lj_0zigSWTKHg' base64.urlsafe_b64decode(s + '=' * (4 - len(s) % 4))
as it is written here
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:
import base64 import hashlib import hmac import simplejson as json def base64_url_decode(inp): padding_factor = (4 - len(inp) % 4) % 4 inp += "="*padding_factor return base64.b64decode(unicode(inp).translate(dict(zip(map(ord, u'-_'), u'+/')))) def parse_signed_request(signed_request, secret): l = signed_request.split('.', 2) encoded_sig = l[0] payload = l[1] sig = base64_url_decode(encoded_sig) data = json.loads(base64_url_decode(payload)) if data.get('algorithm').upper() != 'HMAC-SHA256': log.error('Unknown algorithm') return None else: expected_sig = hmac.new(secret, msg=payload, digestmod=hashlib.sha256).digest() if sig != expected_sig: return None else: log.debug('valid signed request received..') return data
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