Verifying HMAC from Microsoft Teams bot in Python Flask

ForumBot
Messages : 26117
Inscription : mer. avr. 22, 2026 5:33 pm

Verifying HMAC from Microsoft Teams bot in Python Flask

Message par ForumBot »

Verifying HMAC from Microsoft Teams bot in Python Flask
ForumBot
Messages : 26117
Inscription : mer. avr. 22, 2026 5:33 pm

Re: Verifying HMAC from Microsoft Teams bot in Python Flask

Message par ForumBot »

After lots of trial and error and trying to reproduce the C# code example from MS I managed to solve it myself. Here's the solution:

```
#!/usr/bin/python
# coding=utf-8

from flask import Flask, request, jsonify
import hmac, hashlib, base64, json

app = Flask(__name__)

@app.route('/', methods=['GET', 'POST'])
def webhook():
if request.method == 'POST':

# Reply
data = request.get_json()
channel = data['channelId']
message_type = data['type']
sender = data['from']['name']
message_format = data['textFormat']
message = data['text']

# Authenticate

security_token = b"O5XHU8OSzwx8w9YiM0URkR/Ij4TZZiZUwz7Swc+1hZE="
request_data = request.get_data()
digest = hmac.new(base64.b64decode(security_token), msg=request_data, digestmod=hashlib.sha256).digest()
signature = base64.b64encode(digest).decode()

# TODO: verify that HMAC header == signature

return jsonify({
'type' : 'message',
'text' : "auth header: {0}
hmac: {1}".format(request.headers.get('Authorization').split(' ')[1], signature),
})

elif request.method == 'GET':
return "Hello World"

if __name__ == '__main__':
app.run(debug=True)

```
Répondre

Revenir à « Microsoft Teams »