Can you use a HMAC-SHA256 signature in authlib in python?

80 views Asked by At

The authlib documentation discusses how to process HMAC-SHA256 signature methods server side, but there doesn't seem to be anything about how to sign requests with this kind of signature.

The following code fails with a ValueError: Invalid signature method.

auth = OAuth1Auth(
    client_id="...",
    client_secret="...",
    token="...",
    token_secret="...",
    realm="...",
    signature_method= "HMAC-SHA256",
)
r = requests.post(url, auth=auth, data=payload)

Is there a way to issue requests with HMAC-SHA256, or is this not supported?

1

There are 1 answers

1
lepture On

There is a blog post about using HMAC-SHA256 in OAuth 1 client:

https://blog.authlib.org/2023/oauth1-hmac-sha256

Copy the code here:

from authlib.oauth1 import ClientAuth


def hmac_sha256_signature(base_string, client_secret, token_secret):
    text = base_string
    key = escape(client_secret or '')
    key += '&'
    key += escape(token_secret or '')
    signature = hmac.new(to_bytes(key), to_bytes(text), hashlib.sha256)
    sig = binascii.b2a_base64(signature.digest())[:-1]
    return to_unicode(sig)

def sign_rsa_sha256(client, request):
    base_string = generate_signature_base_string(request)
    return hmac_sha256_signature(base_string, client.rsa_key)


ClientAuth.register_signature_method("HMAC-SHA256", sign_rsa_sha256)