Twitter API Post请求错误代码215身份验证数据错误

2024-05-16 01:10:53 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在用MicroPython构建一个运行在NodeMCU ESP8266板上的Twitter机器人。MicroPython不支持OAuth1.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

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

我为MicroPython urequests模块编写了一个小型包装器类,名为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)

cls.__create_auth_header(...)的返回值是一个“OAuth”字符串,与上面链接#1末尾的字符串类似。我已经验证了HMAC-SHA1算法的实现从上面链接2中的样本数据产生相同的输出。我能够通过邮递员发送相同的响应,因此我的API密钥是有效的

我是否正确地创建了请求头

我已将我的代码提交给thisrepo


Tags: tokeyauthurlrequestmicropythonparamspost
1条回答
网友
1楼 · 发布于 2024-05-16 01:10:53

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

从我最初在上面发布的关于creating the signature的链接中,您可以通过百分比编码和加入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)

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

然而,当我使用PostMan调试请求时,它正在工作。我意识到邮递员在计算签名时不知道添加include_entities条目。瞧,当我从这本词典中取出那把钥匙时,错误就消失了

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

相关问题 更多 >