Skip to content

Instantly share code, notes, and snippets.

@jeremiak
Last active December 21, 2015 21:39
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 jeremiak/6369555 to your computer and use it in GitHub Desktop.
Save jeremiak/6369555 to your computer and use it in GitHub Desktop.
I was trying to better understand how OAuth 1 signed requests so I made a quick script to verify the process and hit the Twitter API
from base64 import b64encode
from hashlib import sha1
import hmac
import random
import time
import urllib
import requests
SECRET = 'XXX' #not gonna find my secret here :)
def make_base_param_string(param_dict):
param_dict['oauth_timestamp'] = '%s' % int(time.time())
p = []
for oauth_key in sorted(param_dict.keys()):
x = ({oauth_key: param_dict[oauth_key]})
url_encoded = urllib.urlencode(x)
p.append(url_encoded)
base_string = '&'.join(p)
return base_string
params = {'oauth_callback': 'http://www.tout.com/yo',
'oauth_consumer_key': 'EV9D5UNrbtRcWyOHQIYYrA',
'oauth_nonce': '%s' % int(random.random()*10000000),
'oauth_signature_method': 'HMAC-SHA1',
'oauth_timestamp': int(time.time()),
'oauth_token': 'fiepeyI8XVwFKGo2HYV5y91pspQDLtkaInsWWihcA',
'oauth_version': '1.0'}
method = 'POST'
url = 'https://api.twitter.com/oauth/request_token'
bs = make_base_param_string(params)
y = '%s&%s&%s' % (method, urllib.quote_plus(url), urllib.quote_plus(bs))
key = '%s&%s' % (SECRET, 'dejES5LyjiALH006RsKcQjMzbfcihJAvz3x8M2O5E')
hashed = hmac.new(key, y, sha1)
signature = urllib.quote_plus(b64encode(hashed.digest()))
params['oauth_signature'] = signature
print params
header = 'OAuth oauth_nonce="%s", oauth_callback="%s", oauth_signature_method="HMAC-SHA1", oauth_timestamp="%s", oauth_consumer_key="%s", oauth_signature="%s", oauth_version="1.0", oauth_token="%s"' % (params['oauth_nonce'], urllib.quote_plus(params['oauth_callback']), params['oauth_timestamp'], params['oauth_consumer_key'], params['oauth_signature'], params['oauth_token'])
print header
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment