Twitter API发布请求--错误代码215错误的身份验证数据



我正在MicroPython中构建一个Twitter机器人程序,以便在NodeMCU ESP8266板上运行。MicroPython不支持开箱即用的OAuth 1.0请求,所以我不得不推出自己的请求。我一直在遵循这些写作来构建我的程序:

  1. https://developer.twitter.com/en/docs/basics/authentication/oauth-1-0a/authorizing-a-request
  2. https://developer.twitter.com/en/docs/basics/authentication/oauth-1-0a/creating-a-signature

当我发送POST请求发送推特时,我会得到以下错误响应:{"errors":[{"code":215,"message":"Bad Authentication data."}]}

我为MicroPythonurequests模块编写了一个小包装类,称为oauth_requests

import urequests as requests
class oauth_request:
@classmethod
def post(cls, url, params, key_ring):
""" Post method with OAuth 1.0
Args:
url (str): URL to send request to.
params (dict): Params to append to URL.
key_ring (dict): Dictionary with API keys.
Returns:
Response from POST request.
"""
auth_header = cls.__create_auth_header("POST", url, params, **key_ring)
headers = {"Authorization": auth_header}
url += "?{}".format(
"&".join([
"{}={}".format(cls.__percent_encode(str(k)), cls.__percent_encode(str(v)))
for k, v in params.items()
]))
return requests.post(url, headers=headers)

CCD_ 4的返回值是"0";OAuth";字符串,就像上面链接#1末尾的那个。我已经验证了HMAC-SHA1算法的实现从上面的链接#2中的样本数据产生了相同的输出。我能够通过PostMan发送相同的响应,所以我的API密钥是有效的。

我是否错误地正确创建了请求标头?

我已将我的代码提交给此回购。

我最终找到了解决问题的方法。主要问题是我没有对oauth_signature的值进行百分比编码。然而,即使在那之后,我也得到了一个新的错误,{"errors":[{"code":32,"message":"Could not authenticate you."}]}

从我最初在上面发布的关于创建签名的链接中,您可以从百分比编码构建基本参数字符串,并且""加入像这样的oauth字典:

url_params = {
"status": "Tweeting from the future."
}
oauth = {
"include_entities": "true",
"oauth_consumer_key": consumer_key,
"oauth_nonce": generate_nonce(),
"oauth_signature_method": "HMAC-SHA1",
"oauth_timestamp": 946684800 + time.time(),
"oauth_token": access_token,
"oauth_version": 1.0,
}
oauth.update(url_params)
base_string = percent_encode_and_join(oauth)

(时间值是奇数,因为微ython系统时间纪元从2000年1月1日开始,而不是1970年1月一日(

然而,当我使用PostMan调试请求时,它正在工作。我意识到Postman在计算签名时不知道添加include_entities条目。瞧,当我把那把钥匙从字典里取出来的时候,错误就消失了。

有关代码,请参阅我上面的回购。

相关内容

最新更新