Skip to content

Instantly share code, notes, and snippets.

@Sunno
Last active July 3, 2019 09:58
Show Gist options
  • Save Sunno/66c687e4f4cad4cbbe48 to your computer and use it in GitHub Desktop.
Save Sunno/66c687e4f4cad4cbbe48 to your computer and use it in GitHub Desktop.
Check mandrill webhook signature in django
"""
This has been adapted from http://www.ahwkong.com/post/2015/02/04/authenticate-mandrill-webhook-call/
Not my algorithm
"""
import hashlib
import hmac
from django.conf import settings
"""
For django
"""
def _calc_signature(raw, key):
hashed = hmac.new(key, raw, hashlib.sha1)
return hashed.digest().encode("base64").rstrip('\n')
# NOT a view
def verify_mandrill_signature(request):
"""
Mandrill includes an additional HTTP header with webhook POST requests,
X-Mandrill-Signature, which will contain the signature for the request.
To verify a webhook request, generate a signature using the same key
that Mandrill uses and compare that to the value of the
X-Mandrill-Signature header.
:return: True if verified valid
"""
mandrill_key = settings.MANDRILL_WEBHOOK_KEY #remember to set this variable in your settings, it's not the same as your mandrill api key
mandrill_signature = request.META['HTTP_X_MANDRILL_SIGNATURE']
signed_data = request.build_absolute_uri(reverse('mail_web_hook')) # this is url where webhook is posting to. Replace 'mail_web_hook' by your named url for your webhook.
sorted_key = sorted(request.POST)
for k in sorted_key:
signed_data += k
signed_data += request.POST[k]
expected_signature = _calc_signature(signed_data, mandrill_key)
return expected_signature == mandrill_signature
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment