How to optionally sign webhook events

Third party services (e.g. Stripe) optionally sign webhook events to verify it is them sending events. If the third party you use does not provide an SDK or official library for verifying signatures, you can manually verify the signature with this snippet.

# urls.py
from django.conf.urls import url
from django.views.decorators.csrf import csrf_exempt

from .views import WebhookView

urlpatterns = [
    url(r'^webhook$', csrf_exempt(WebhookView.as_view())),
]

# views.py
import base64
import hashlib
import hmac

from django.conf import settings
from django.http import HttpResponse
from django.views import View


def verify(request):
    signature = str.encode(request.META['HTTP_WEBHOOK_SIGNATURE'])

    digest = hmac.new(
        key=str.encode(settings.WEBHOOK_SECRET),
        msg=request.body,
        digestmod=hashlib.sha1).digest()

    expected_signature = base64.b64encode(digest)

    return hmac.compare_digest(signature, expected_signature)


class WebhookView(View):
    def dispatch(self, request, *args, **kwargs):
        if not verify(request):
            return HttpResponse(status=400)

        return super().dispatch(request, *args, **kwargs)

Django Replies 0 Views 90 Users 1

Suggested Topics

Django Updated on April 1, 2020, 9:12 p.m. Replies Views 55

Django Updated on April 6, 2020, 12:50 a.m. Replies Views 42

Django Updated on April 7, 2020, 9:54 p.m. Replies Views 73

Django Updated on April 13, 2020, 11:35 a.m. Replies Views 143