I have been using libraries to handle OAuth so far, but lately I have been digging deeper, trying to understand the underlying OAuth process. I am currently trying to connect to the Tumblr API v2 using OAuth 1.0a using this simple code:
import urllib, urllib2, time, random, hmac, base64, hashlib
def makenonce():
random_number = ''.join( str( random.randint( 0, 9 ) ) for _ in range( 40 ) )
m = hashlib.md5( str( time.time() ) + str( random_number ) )
return m.hexdigest()
def encodeparams(s):
return urllib.quote( str( s ), safe='~' )
consumer_key = '97oAujQhSaQNv4XDXzCjdZlOxwNyhobmDwmueJBCHWsFFsW7Ly'
consumer_secret = '5q1dpF659SOgSUb0Eo52aAyoud8N8QOuJu6enCG92aDR6WoMlf'
request_tokenURL = 'http://www.tumblr.com/oauth/request_token'
oauth_parameters = {
'oauth_consumer_key' : consumer_key,
'oauth_nonce' : makenonce(),
'oauth_timestamp' : str(int(time.time())),
'oauth_signature_method' : "HMAC-SHA1",
'oauth_version' : "1.0"
}
normalized_parameters = encodeparams( '&'.join( ['%s=%s' % ( encodeparams( str( k ) ), encodeparams( str( oauth_parameters[k] ) ) ) for k in sorted( oauth_parameters )] ) )
normalized_http_method = 'POST'
normalized_http_url = encodeparams( request_tokenURL )
signature_base_string = '&'.join( [normalized_http_method, normalized_http_url, normalized_parameters] )
oauth_key = consumer_secret + '&'
hashed = hmac.new( oauth_key, signature_base_string, hashlib.sha1 )
oauth_parameters['oauth_signature'] = base64.b64encode( hashed.digest() )
oauth_header = 'Authorization: OAuth realm="http://www.tumblr.com",' + 'oauth_nonce="' + oauth_parameters['oauth_nonce'] + '",' + 'oauth_timestamp="' + oauth_parameters['oauth_timestamp'] + '",' + 'oauth_consumer_key="' + oauth_parameters['oauth_consumer_key'] + '",' + 'oauth_signature_method="HMAC-SHA1",oauth_version="1.0",oauth_signature="' + oauth_parameters['oauth_signature'] +'"'
req = urllib2.Request( request_tokenURL )
req.add_header( 'Authorization', oauth_header )
print urllib2.urlopen( req ).read()
Instead of an OAuth request token, Tumblr returns HTTP Error 401: Unauthorized .
Things I tried without success:
- Changed
oauth_versionfrom "1.0" to "1.0a" and changed it again. - The OAuth manual pledged to add '&' at the end
consumer_secretto receive oauth_key. I tried removing '&' later to see if this had changed. - , OAuth, .
- ":"
oauth_header, . .
?