Create a gist now

Instantly share code, notes, and snippets.

Sign and verify requests
import hmac
import base64
import hashlib
# simplejson is available at:
import simplejson as json
class RequestSigner(object):
def verify_and_load_signed_request(self, signed_request, secret):
"""Verify the signature, and return decoded data from a signed_request value"""
sig, payload = signed_request.split(u'.', 1)
sig = self.base64_url_decode(sig)
data = json.loads(self.base64_url_decode(payload))
expected_sig =
secret, msg=payload, digestmod=hashlib.sha256).digest()
# allow the signed_request to function for upto 1 day
if sig == expected_sig:
return data
except ValueError:
pass # ignore if can't split on dot
def sign_request(self, object, secret):
"""Generate a signed_request value based on current state"""
payload = self.base64_url_encode(json.dumps(object))
sig = self.base64_url_encode(
secret, msg=payload, digestmod=hashlib.sha256).digest())
return sig + '.' + payload
def base64_url_decode(data):
data = data.encode(u'ascii')
data += '=' * (4 - (len(data) % 4))
return base64.urlsafe_b64decode(data)
def base64_url_encode(data):
return base64.urlsafe_b64encode(data).rstrip('=')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment