Quantcast
Channel: Sullerton » Facebook
Viewing all articles
Browse latest Browse all 2

Checking Facebook’s signed_request in Python

$
0
0

I’m still not exactly sure why, but I had the hardest time trying to port facebook’s php example of how to check the signed_request that is passed to facebook apps. I finally found this pull request that had the solution. Not sure why this has not been added to the facebook python module already.

Here’s what it looks like for me (i’m just using it as a utility function at this point):

from django.conf import settings
import hmac
import hashlib
import base64
import json
 
def validate_signed_fb_request(signed_request):
    """Return dictionary with signed request data."""
    try:
      l = signed_request.split('.', 2)
      encoded_sig = str(l[0])
      payload = str(l[1])
    except IndexError:
      raise ValueError("'signed_request' malformed")
 
    sig = base64.urlsafe_b64decode(encoded_sig + "=" * ((4 - len(encoded_sig) % 4) % 4))
    data = base64.urlsafe_b64decode(payload + "=" * ((4 - len(payload) % 4) % 4))
 
    data = json.loads(data)
 
    if data.get('algorithm').upper() != 'HMAC-SHA256':
      raise ValueError("'signed_request' is using an unknown algorithm")
    else:
      expected_sig = hmac.new(settings.FACEBOOK_APP_SECRET, msg=payload, digestmod=hashlib.sha256).digest()
 
    if sig != expected_sig:
      raise ValueError("'signed_request' signature mismatch")
    else:
      return data

Viewing all articles
Browse latest Browse all 2

Latest Images

Trending Articles





Latest Images