HMAC-SHA256 for OAuth 1.0

Implement HMAC-SHA256 signature method for OAuth 1.0 client

The default supported signature methods for OAuth 1.0 are HMAC-SHA1, PLAINTEXT, and RSA-SHA1. It's important to note that OAuth 1 is a protocol, not a framework, and there are currently no updates for the OAuth 1 RFC.

However, some companies have chosen to implement alternative signature methods for OAuth 1.0, such as HMAC-SHA256. While our documentation provides an example of how to create a server using this method, we currently lack documentation for the client-side implementation. Nevertheless, implementing the HMAC-SHA256 signature method on the client side is a relatively straightforward task.

Let's take a look at the code in authlib.oauth1.rfc5849.signature. The HMAC-SHA1 signature method is defined as follows:

def hmac_sha1_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.sha1)
sig = binascii.b2a_base64(signature.digest())[:-1]
return to_unicode(sig)
def sign_hmac_sha1(client, request):
base_string = generate_signature_base_string(request)
return hmac_sha1_signature(base_string, client.client_secret, client.token_secret)

To implement the HMAC-SHA256 signature method, it's quite straightforward. We can essentially copy the HMAC-SHA1 signature method and make one key change, replacing the SHA1 hash method with SHA256:

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_hmac_sha256(client, request):
base_string = generate_signature_base_string(request)
return hmac_sha256_signature(base_string, client.client_secret, client.token_secret)

By making this modification, you'll have an HMAC-SHA256 signature method that mirrors the structure of the HMAC-SHA1 method but uses SHA256 for hashing.

And finally, you need to register the signature method:

from authlib.oauth1 import ClientAuth
ClientAuth.register_signature_method("HMAC-SHA256", sign_hmac_sha256)

Once you've registered the HMAC-SHA256 signature method, you can use it in all your OAuth 1.0 clients.