Skip to content

Embed URL

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Sign and verify requests
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('=')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Something went wrong with that request. Please try again.