lundi 30 mars 2015

How can I parse signed_request from facebook graph api in django 1.7

Facebook sends a POST request to access a custom tab in a page and that request comes with a parameter signed_request which is encoded.


I tried to use this code to decode it:



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':
print('Unknown algorithm')
return None
else:
expected_sig = hmac.new(secret, msg=payload, digestmod=hashlib.sha256).digest()

if sig != expected_sig:
return None
else:
print('valid signed request received..')
return data


It is not working for me. Just returns None.


How to fix this? or is there any other way to decode the signed_request?


Aucun commentaire:

Enregistrer un commentaire