我一直在关注Twitter的3条腿oauth设置指南: https://dev.twitter.com/docs/auth/implementing-sign-twitter
第1步:获取请求令牌
对于他们的身份验证,步骤1要求发出包含base64编码的公钥和密钥的发布请求。
key = "CONSUMER_KEY"
secret = "CONSUMER_SECRET"
auth = base64.encodestring("%s:%s" % (key, secret)).replace("\n", "")
data = {}
data["grant_type"] = "client_credentials"
headers = {}
headers["Authorization"] = "Basic " + auth
headers["Content-Type"] = "application/x-www-form-urlencoded;charset=UTF-8"
headers["Accept-Encoding"] = "gzip"
response = requests.post("https://api.twitter.com/oauth2/token",
headers=headers, data=data)
此第一个请求返回有效的响应代码200以及访问令牌。响应如下: {u'access_token':u'AAAAAAAAAAAAAAAAAAAAAHHHHH ...... vncbi',u'token_type':u'bearer'}
第2步:重定向用户
这就是问题发生的地方。根据文档,用户只需要重定向到格式如下的授权URL:
https://api.twitter.com/oauth/authenticate?oauth_token=AAAAAAAAAAAAAAAAAAAAAHHHHH... ...vncbi
然而,当我到达此页面时,我收到一条错误消息:
我错过了什么吗?正在生成access_token而没有问题。我不确定此消息是否显示,因为我在此过程的早期设置错误。我也不确定如何检查oauth令牌是否已过期。
答案 0 :(得分:0)
实际上,您一直关注https://dev.twitter.com/docs/api/1.1/post/oauth2/token,这是完全不同的,例如仅用于公共资源而非私有状态更新。对于三步结账https://gist.github.com/ib-lundgren/4487236或更好的http://twython.readthedocs.org/en/latest/
如果您只想访问公共资源(如用户时间线),可以通过以下代码执行此操作。
# OBS: If you want to look at per user details and make status updates
# you want the OAuth1 version. This is only for publicly available
# resources such as user timelines.
from requests_oauthlib import OAuth2Session
from oauthlib.oauth2 import BackendApplicationClient
# Credentials you get from registering a new application
client_id = '<the id you get from github>'
client_secret = '<the secret you get from github>'
# TODO remove
client_id = 'VVq5UniipB5nXFAqtTA'
client_secret = 'PlaHnaSDbeY4eYkv8XiqxS1nzGWyKoq5WYSNjdeaw'
client_id = 'I1Xi7fOeYnA9jabyvGUaZxY20'
client_secret = 'k5PZpINooRpjAfQccGwLUr2ZMEtRJtoX8cKaooHjKewWupxRBG'
token_url = 'https://api.twitter.com/oauth2/token'
client = BackendApplicationClient(client_id)
twitter = OAuth2Session(client_id, client=client)
headers = {
'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8'
}
twitter.fetch_token(token_url, headers=headers, auth=(client_id, client_secret))
# Only public resources available to this application-only clients.
r = twitter.get('https://api.twitter.com/1.1/statuses/user_timeline.json?count=100&screen_name=twitterapi')
print r.content
确保使用库的github版本
pip install git+https://github.com/idan/oauthlib.git
pip install git+https://github.com/requests/requests-oauthlib.git