Skip to content

Instantly share code, notes, and snippets.

@ainmosni
Created February 23, 2016 19:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ainmosni/af9fec4601c2265db25d to your computer and use it in GitHub Desktop.
Save ainmosni/af9fec4601c2265db25d to your computer and use it in GitHub Desktop.
Just a quick and dirty implementation of the twitter oauth signature algorithm.
from urllib.parse import quote, urlencode
from base64 import b64encode
from collections import OrderedDict
import hmac
percent_encode = lambda x: quote(x, safe='-._~')
def generate_oauth_signature(method: str,
url: str,
*,
consumer_secret: str,
oauth_token_secret: str=None,
auth_params: dict=None,
query_params: dict=None,
post_params: dict=None) -> str:
full_string = method.upper() + '&' + percent_encode(url) + '&'
parameter_dict = {}
if auth_params:
parameter_dict.update(auth_params)
if query_params:
parameter_dict.update(query_params)
if post_params:
parameter_dict.update(post_params)
sorted_params = OrderedDict()
for key in sorted(parameter_dict.keys()):
sorted_params[key] = parameter_dict[key]
parameter_str = urlencode(sorted_params, safe='-._~', quote_via=quote)
full_string += percent_encode(parameter_str)
signing_key = percent_encode(consumer_secret) + '&'
if oauth_token_secret:
signing_key += percent_encode(oauth_token_secret)
signature = hmac.new(signing_key.encode('utf-8'),
full_string.encode('utf-8'),
digestmod='sha1')
return b64encode(signature.digest())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment