public
Last active

Sign and verify requests

  • Download Gist
RequestSigner.py
Python
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39
import hmac
import base64
import hashlib
# simplejson is available at: http://pypi.python.org/pypi/simplejson/
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"""
try:
sig, payload = signed_request.split(u'.', 1)
sig = self.base64_url_decode(sig)
data = json.loads(self.base64_url_decode(payload))
 
expected_sig = hmac.new(
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(hmac.new(
secret, msg=payload, digestmod=hashlib.sha256).digest())
return sig + '.' + payload
 
@staticmethod
def base64_url_decode(data):
data = data.encode(u'ascii')
data += '=' * (4 - (len(data) % 4))
return base64.urlsafe_b64decode(data)
 
@staticmethod
def base64_url_encode(data):
return base64.urlsafe_b64encode(data).rstrip('=')

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.