Last active
November 21, 2016 19:14
-
-
Save tstachl/27b502e17da3c965bebe to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def parse_signed_request(request, max_age=3600) | |
# Split the signed request on the first period. The result is two strings: the hashed Based64 context signed with the consumer secret and the Base64 encoded context itself. | |
encoded_sig, enc_envelope = request.split('.', 2) | |
envelope = JSON.parse(base64_url_decode(enc_envelope)).with_indifferent_access # Needs ActiveSupport | |
algorithm = envelope[:algorithm] | |
# ADDITIONAL: Check the algorithm is HMAC SHA-256 | |
if algorithm != 'HMACSHA256' | |
raise 'Invalid request. (Unsupported algorithm.)' | |
end | |
# ADDITONAL: Making sure the request is not older than specified `max_age` | |
if Time.parse(envelope[:issuedAt]).to_i < Time.now.to_i - max_age | |
raise 'Invalid request. (Too old.)' | |
end | |
# Use the HMAC SHA-256 algorithm to hash the Base64 encoded context and sign it using your consumer secret. | |
hex = OpenSSL::HMAC.hexdigest('sha256', key, enc_envelope).split.pack('H*') | |
# Base64 encode the string created in the previous step. | |
base_decoded_sig = base64_url_decode(encoded_sig) | |
# Compare the Base64 encoded string with the hashed Base64 context signed with the consumer secret you received in step 2. | |
if base_decoded_sig != hex | |
raise 'Invalid request. (Invalid signature.)' \ | |
end | |
envelope | |
end | |
def key | |
ENV['DESK_SHARED_KEY'] # from the canvas integration URL window | |
end | |
def base64_url_decode(str) | |
str += '=' * (4 - str.length.modulo(4)) | |
Base64.decode64(str.tr('-_','+/')) | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment