Wednesday, January 23, 2019

Microsoft Teams HMAC verification using Python 3


The example provided by Microsoft is in C#.

Here is the equivalent in Python 3:

from hashlib import sha256
import hmac
import base64

ms_teams_auth_token = <"Provided by Teams upon outgoing webhook bot creation">

def return_calculated_hmac(post_body):

    key = base64.b64decode(bytes(ms_teams_auth_token,'utf-8')) 
    raw = bytes(post_body,'utf-8')  
    hashed = hmac.new(key, raw, sha256)
    
    # The signature
    return f"HMAC {base64.b64encode(hashed.digest()).decode('utf-8')}"

If the value returned by this function matches the provided HMAC key (in the Authorization header) then the request is legit.

2 comments: