我坚持使用Twitter登录。现在我意识到,这是一个步骤(与OAuth2相比相当愚蠢):
向/ request_token端点发出POST请求以获取初始令牌
使用(1)中的令牌参数将用户重定向到/进行身份验证以获取另一个令牌
使用来自(2)的令牌向/ access-token发出另一个POST请求,最后获得所需的令牌。
现在我有点困惑(1):twitter API总是返回ERROR 215,错误验证数据。
代码是这样的:
key = b"my_key&"
raw_init = "POST" + "&" + quote("https://api.twitter.com/1.1/oauth/request_token", safe='')
time_param = str(calendar.timegm(time.gmtime()))
raw_params = quote('oauth_callback', safe='') + "=" + quote('http://example.com/twitter-auth/', safe='')
raw_params += "&" + quote('oauth_consumer_key', safe='') + "=" + quote('consumer_key', safe='')
raw_params += "&" + quote('oauth_nonce', safe='') + "=" + quote('aAbBcDadadwrwwrwrwr', safe='')
raw_params += "&" + quote('oauth_signature_method', safe='') + "=" + quote('HMAC-SHA1', safe='')
raw_params += "&" + quote('oauth_timestamp', safe='') + "=" + quote(time_param, safe='')
raw_params += "&" + quote('oauth_version', safe='') + "=" + quote('1.0', safe='')
#
raw_params = quote(raw_params, safe='')
raw_final = bytes(raw_init + "&" + raw_params, encoding='utf-8')
hashed = hmac.new(key, raw_final, sha1)
request.raw_final = hashed
request.auth_header = base64.b64encode(hashed.digest()).decode()
上面的代码为Authorization标头创建了签名。
POST请求:
url = 'https://api.twitter.com/1.1/oauth/request_token'
data = {}
oauth_sign_method = "HMAC-SHA1"
headers = {'Authorization': 'OAuth oauth_nonce="aAbBcDadadwrwwrwrwr"' +
'oauth_callback="' + quote('http://example.com/twitter-auth/', safe='') + '",' +
'oauth_signature_method="HMAC-SHA1",' +
'oauth_timestamp="' + time_param + '",'+
'oauth_consumer_key="consumer_key",'+
'oauth_signature="' + base64.b64encode(hashed.digest()).decode() + '",'+
'oauth_version="1.0"'}
r = requests.post(url, data=json.dumps(data), headers=headers)
answer = json.loads(r.text)
request.twitter_answer = answer
答案总是错误215 - 错误验证数据。知道为什么吗?
答案 0 :(得分:0)
我也正在为twitter oauth构建Django后端。
请到这里查看python代码,我成功完成了代码片段。