OAuth 生成过期的凭证令牌
我一直在按照Twitter的三步认证设置指南进行操作:https://dev.twitter.com/docs/auth/implementing-sign-twitter
第一步:获取请求令牌
在他们的认证过程中,第一步需要发送一个包含经过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'}第二步:重定向用户
问题出现在这里。根据文档,用户接下来只需要被重定向到一个格式化好的授权网址,格式如下:
https://api.twitter.com/oauth/authenticate?oauth_token=AAAAAAAAAAAAAAAAAAAAAHHHHH... ...vncbi
但是当我到达这个页面时,却出现了一个错误信息:

我是不是漏掉了什么?访问令牌生成没有问题。我不确定这个错误信息是否是因为我在之前的步骤中设置错误了什么。我也不太清楚如何检查oauth令牌是否过期。
1 个回答
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