Skip to content

Instantly share code, notes, and snippets.

@tstachl
Last active November 21, 2016 19:14
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save tstachl/27b502e17da3c965bebe to your computer and use it in GitHub Desktop.
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