Last active
June 21, 2022 21:26
-
-
Save jacinator/928a6580e33a0f90ac02a51ba54daa79 to your computer and use it in GitHub Desktop.
Example: verify HMAC authorization header with Python and Flask
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
"""Verify a HMAC authorization header using Flask | |
This is how to verify an HMAC authorization header against the body of | |
a request using Flask. | |
When I was creating a Flask app to support a Microsoft Teams outgoing | |
webhook I had some difficulty finding examples or tutorials. I found | |
some example code from Microsoft in Node.js and one in C#. I spent a | |
few hours carefully reading through it and converting the process to | |
Python. Hopefully my posting this as a gist can save some other people | |
a little bit of time. | |
Examples that I found: | |
https://github.com/OfficeDev/Microsoft-Teams-Samples/blob/main/samples/outgoing-webhook/nodejs/app.js | |
https://github.com/OfficeDev/microsoft-teams-sample-outgoing-webhook/blob/23eb61da5a18634d51c5247944843da9abed01b6/WebhookSampleBot/Models/AuthProvider.cs | |
""" | |
import base64 | |
import hashlib | |
import hmac | |
from flask import Flask, abort, jsonify, request | |
TOKEN = base64.b64decode('<your HMAC token string>') | |
@app.route('/', methods=['POST']) | |
def route(): | |
auth = request.headers['Authorization'] # 'HMAC <value>' | |
auth_token = base64.b64decode(auth[5:]) # b'<value>' | |
hmac_token = hmac.digest(TOKEN, request.get_data(), hashlib.sha256) | |
if hmac_token != auth_token: | |
abort('HMAC does not match') | |
return jsonify({ | |
'text': 'OK', | |
'type': 'message', | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment