无法获得 OAuth“请求令牌"在使用 Python 使用 Tumblr API 时 [英] Unable to get OAuth "Request Token" while working with the Tumblr API using Python

查看:19
本文介绍了无法获得 OAuth“请求令牌"在使用 Python 使用 Tumblr API 时的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

到目前为止,我一直在使用库来处理 OAuth,但最近我一直在深入挖掘,试图了解底层的 OAuth 过程.目前,我正在尝试使用 OAuth 1.0a 连接到 Tumblr API v2用这个简单的代码:

import urllib, urllib2, time, random, hmac, base64, hashlibdef makenonce():random_number = ''.join( str( random.randint( 0, 9 ) ) for _ in range( 40 ) )m = hashlib.md5( str( time.time() ) + str( random_number ) )返回 m.hexdigest()定义编码参数:返回 urllib.quote( str( s ), safe='~' )# 来自使用虚拟 Tumblr 帐户创建的测试应用程序的实际密钥和秘密消费者密钥 = '97oAujQhSaQNv4XDXzCjdZlOxwNyhobmDwmueJBCHWsFFsW7Ly'消费者秘密 = '5q1dpF659SOgSUb0Eo52aAyoud8N8QOuJu6enCG92aDR6WoMlf'#oauth 网址request_tokenURL = 'http://www.tumblr.com/oauth/request_token'#oauth 参数oauth_parameters = {'oauth_consumer_key':消费者密钥,'oauth_nonce' : makenonce(),'oauth_timestamp' : str(int(time.time())),'oauth_signature_method':HMAC-SHA1",'oauth_version':1.0"}normalized_pa​​rameters = encodeparams( '&'.join( ['%s=%s' % ( encodeparams( str( k ) ), encodeparams( str( oauth_parameters[k] ) ) ) for k in sorted( oauth_parameters )] ) )# 由于我目前只关注获取请求令牌,因此我将其设置为 POST.normalized_http_method = 'POST'normalized_http_url = encodeparams( request_tokenURL )signature_base_string = '&'.join( [normalized_http_method, normalized_http_url, normalized_pa​​rameters] )oauth_key = consumer_secret + '&'散列 = hmac.new( oauth_key, signature_base_string, hashlib.sha1 )oauth_parameters['oauth_signature'] = base64.b64encode( hashed.digest() )oauth_header = '授权: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="' + ['auth_parameters'] +'"'# 上面代码生成的示例 oauth_header:#授权:OAuth的境界= http://www.tumblr.com",oauth_nonce = c200a0e06f30b84b851ac3e99a71054b",oauth_timestamp = 1315231855",oauth_consumer_key = 97oAujQhSaQNv4XDXzCjdZlOxwNyhobmDwmueJBCHWsFFsW7Ly",oauth_signature_method = HMAC-SHA1",oauth_version = 1.0",oauth_signature="kVAlmwolCX0WJIvTF9MB2UV5rnU="req = urllib2.Request( request_tokenURL )req.add_header('授权', oauth_header)# 如果一切顺利,Tumblr 应该向我发送 oauth 请求令牌.打印 urllib2.urlopen( req ).read()

Tumblr 返回HTTP 错误 401:未经授权,而不是 OAuth 请求令牌.

我尝试过但没有成功的事情:

  1. oauth_version 从1.0"更改为1.0a",然后再次更改回来.
  2. OAuth 指南要求添加&"在 consumer_secret 的末尾获取 oauth_key.我尝试删除&"稍后再看看这是否有什么不同.
  3. 检查 OAuth 参数是否已排序,并且是.
  4. 没有将字符串Authorization:"添加到oauth_header,然后稍后再添加回来.两者都没有任何区别.

我哪里出错了?

解决方案

对上面的代码做了2个简单的修改后解决了:

  1. normalized_http_method = 'GET' #not POST
  2. oauth_header = 'OAuth realm="http://www...' # 授权"这个词是不必要的.我之前已经把这个去掉了在我尝试过但没有任何成功的事情"中,但 (1) 中列出的错误让我偏离了轨道.解决 (1) 后,我可以看到授权"确实是不必要的.

当我最终做对时,Tumblr 发给我的 OAuth 请求令牌:oauth_token=mbRUgyDkPePfkEztiLELMqUl1kyNXEcaTCCwpb7SoXDF9mhiTF&oauth_token_secret=5pXllXGKA8orAaUat1G7ckIfMfYup8juMBAgEELUkeMZoC3&codeuvthed

这是一个一次性令牌,为了完整起见,我将其列在此处.

I've been using libraries to handle OAuth so far, but lately I've been digging deeper trying to understand the underlying OAuth process. Currently, I'm trying to connect to Tumblr API v2 using OAuth 1.0a with 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='~' )

# Actual key and secret from a test app created using a dummy Tumblr account
consumer_key = '97oAujQhSaQNv4XDXzCjdZlOxwNyhobmDwmueJBCHWsFFsW7Ly'
consumer_secret = '5q1dpF659SOgSUb0Eo52aAyoud8N8QOuJu6enCG92aDR6WoMlf'

#oauth URLs
request_tokenURL = 'http://www.tumblr.com/oauth/request_token'

#oauth params
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 )] ) )
# Since I'm focusing only on getting the request token for now, I set this to POST.
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'] +'"'

# sample oauth_header generated by the code above:
# Authorization: OAuth realm="http://www.tumblr.com",oauth_nonce="c200a0e06f30b84b851ac3e99a71054b",oauth_timestamp="1315231855",oauth_consumer_key="97oAujQhSaQNv4XDXzCjdZlOxwNyhobmDwmueJBCHWsFFsW7Ly",oauth_signature_method="HMAC-SHA1",oauth_version="1.0",oauth_signature="kVAlmwolCX0WJIvTF9MB2UV5rnU="


req = urllib2.Request( request_tokenURL )
req.add_header( 'Authorization', oauth_header )
# If all goes well, Tumblr should send me the oauth request token.
print urllib2.urlopen( req ).read()

Instead of the OAuth Request token, Tumblr returns HTTP Error 401: Unauthorized.

Things I've tried without any success:

  1. Changed oauth_version from "1.0" to "1.0a", and changed it back again.
  2. A guide on OAuth mandated adding the '&' at the end of consumer_secret to get the oauth_key. I tried removing the '&' later to see if that made any difference.
  3. Checked if the OAuth parameters were sorted, and they were.
  4. Did not add the string "Authorization: " to oauth_header, then added it back later. Neither made any difference.

Where have I gone wrong?

解决方案

Solved it after making just 2 simple changes in the above code:

  1. normalized_http_method = 'GET' #not POST
  2. oauth_header = 'OAuth realm="http://www...' # The word "Authorization" is unnecessary. I had taken this out earlier as listed in "Things I've tried without any success", but the error listed in (1) threw me off track. With (1) solved, I could see how "Authorization" was indeed unnecessary.

The OAuth Request token Tumblr sent me when I finally got it right: oauth_token=mbRUgyDkPePfkEztiLELMqUl1kyNXEcaTCCwpb7SoXDF9mhiTF&oauth_token_secret=5pXllXGKA8orAaUat1G7ckIfMfYup8juMBAgEELUkeMZoC3pv6&oauth_callback_confirmed=true

This is a one-time only token and I've listed it here just for the sake of completeness.

这篇关于无法获得 OAuth“请求令牌"在使用 Python 使用 Tumblr API 时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆