Login

Verify events sent to your webhook endpoints

Author:
santos22
Posted:
March 18, 2020
Language:
Python
Version:
Not specified
Tags:
signature third-party webhook hmac
Score:
0 (after 0 ratings)

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.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
# 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)

More like this

  1. Automatically setup raw_id_fields ForeignKey & OneToOneField by agusmakmun 6 months ago
  2. Crispy Form by sourabhsinha396 7 months ago
  3. ReadOnlySelect by mkoistinen 7 months, 1 week ago
  4. Verify events sent to your webhook endpoints by santos22 8 months, 1 week ago
  5. Django Language Middleware by agusmakmun 8 months, 2 weeks ago

Comments

Please login first before commenting.