Hi there!
Hi everyone - I was wondering if someone could help with securing a GitHub webhook request in Django.
The majority of the guides I’ve found for this (such as this: Handling GitHub webhooks with Django · GitHub) generate the “signature” by using request.body, from the webhook’s request itself. However, in all of my cases request.body is empty!
Please help a poor dev who is tired and just wants his webhooks to be secure! My code below:
@csrf_exempt
def webhook_update(request):
# AUTH: https://gist.github.com/grantmcconnaughey/6169d8b7a2e770e85c5617bc80ed00a9
if not "X-Hub-Signature" in request.headers:
return HttpResponseForbidden("Invalid")
github_signature = request.META["HTTP_X_HUB_SIGNATURE"]
signature = hmac.new(os.getenv("SECRET_TOKEN"), request.body, hashlib.sha1)
expected_signature = "sha1=" + signature.hexdigest()
if not hmac.compare_digest(github_signature, expected_signature):
return HttpResponseForbidden("Invalid signature header")
Confusingly the sample I reference above highlights that the “payload” could be in request.body or in request.POST[‘payload’], but this is AFTER the signature
variable has been generated from the hmac.new()
statement, so I wanted to ask around before blindly experimenting.
# Sometimes the payload comes in as the request body, sometimes it comes in
# as a POST parameter. This will handle either case.
if 'payload' in request.POST:
payload = json.loads(request.POST['payload'])
else:
payload = json.loads(request.body)
GitHub docs on securing webhooks: Securing your webhooks - GitHub Docs
TIA!
Rich