1

我正在尝试使用创建应用程序并选中“允许此应用程序用于使用 Twitter 登录”的 api 访问 Twitter,然后我按照以下步骤操作:

https://dev.twitter.com/docs/api/1/post/oauth/request_token
https://dev.twitter.com/docs/auth/authorizing-request
https://dev.twitter.com/docs/auth/creating-signature

但我得到

urllib2.HTTPError: HTTP Error 401: Unauthorized

所以我一定是做错了什么或错过了什么

有人能发现我的错误吗?

import urllib2
import time
import urllib
import hashlib
import hmac
import base64

def escape(s):
    return urllib.quote(s, safe='~')

consumer_key = 'yBsHl3G6MqXx9JpnoLoGbA'
consumer_secret = 'JBk5oUDLSuNAXxdBHrDmoUFxemw7IJ1a2yWPmCydX7w'
http_method =  'POST'
base_url = 'https://api.twitter.com/oauth/request_token'
oauth_token_secret =  ''

data={'oauth_callback':'http://localhost.de:8000/accounts/callback/twitter'}

header = {
    'oauth_consumer_key': consumer_key,
    'oauth_timestamp': str(int(time.time())),
    'oauth_nonce': hashlib.md5(str(time.clock())).hexdigest(),
    'oauth_version': '1.0',
    'oauth_signature_method': 'HMAC-SHA1'
}
header.update(data)

paramstr = ''
for k in sorted(header):
    paramstr+=escape(k)+'='+escape(header[k])+'&'
paramstr = paramstr[:-1]
print paramstr

sig_base_str = http_method.upper()+'&'+escape(base_url)+'&'+escape(paramstr)
print sig_base_str
key = escape(consumer_secret)+'&'+escape(oauth_token_secret) 
signature = base64.b64encode(hmac.new(key, sig_base_str, hashlib.sha1).digest())

header['oauth_signature'] = signature
header_str = 'OAuth '
for k in sorted(header):
    header_str+=escape(k)+'="'+escape(header[k])+'", '
header_str = header_str[:-2]
print header_str

req=urllib2.Request(base_url, data=urllib.urlencode(data))
req.add_header('Authorization', header_str)
print urllib2.urlopen(req).read()

我知道有这样做的库,但我想编写自己的代码用于测试目的

4

1 回答 1

2

我自己解决了。twitter 文档不是 100% 正确的。例如这里

https://dev.twitter.com/docs/api/1/post/oauth/request_token

他们说授权标头应该是这样的

OAuth oauth_nonce="K7ny27JTpKVsTgdyLdDfmQQWVLERj2zAK5BslRsqyw", oauth_callback="http%3A%2F%2Fmyapp.com%3A3005%2Ftwitter%2Fprocess_callback", oauth_signature_method="HMAC-SHA1", oauth_timestamp="1300228849", oauth_consumer_key="OqEqJeafRSF11jBMStrZz", oauth_signature="Pc%2BMLdv028fxCErFyi8KXFM%2BddU%3D", oauth_version="1.0"

但这是错误的,您不应该添加oauth_callback="http%3A%2F%2Fmyapp.com%3A3005%2Ftwitter%2Fprocess_callback"到授权标头

于 2013-10-06T10:44:53.800 回答