D
D
Denis Kazakov2020-01-10 19:53:43
ruby
Denis Kazakov, 2020-01-10 19:53:43

How to adapt Github webhooks signature validation Ruby script for Python3?

I wrote a small application in Flask to pull the main application from the repository when a webhook arrives that a commit has been made to the master. There is a manual for Ruby on GitHub, but I can't adapt it to Python3.
I tried to do it like this:

from flask import Flask, request
from hmac import HMAC, compare_digest
from hashlib import sha1

app = Flask(__name__)

def verify_signature(req):
     received_sign = req.headers.get('X-Hub-Signature').split('sha1=')[-1].strip()
     secret = 'my_secret_string'.encode()
     expected_sign = HMAC(key=secret, msg=req.data, digestmod=sha1).hexdigest()
     return compare_digest(received_sign, expected_sign)

@app.route('/webhook', methods=['POST', 'GET'])
def webhook():
    if request.method == 'POST':
        if verify_signature(request):
            do_smth()
            return 'Successfully', 200
        return 'Forbidden', 403
    return 'Not allowed', 405

I also tried using sha1(...).hexdigest() and compare_digest() from the secrets module, but the hashes are always different.
What am I doing wrong?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Denis Kazakov, 2020-01-12
@KazakovDenis

Corrected the code in the question, now it works

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question