针对Twitter API GET和POST方法的RestSharp中的OAuth1身份验证

针对Twitter API GET和POST方法的RestSharp中的OAuth1身份验证,twitter,restsharp,oauth-1.0a,Twitter,Restsharp,Oauth 1.0a,使用Postman,我能够使用TwitterAPI,使用Postman的OAuth 1.0授权,成功地查询和创建定制的受众。然而,当尝试对RestSharp执行相同操作时,我得到了一个未经授权的错误 “未经授权的访问”-“此请求未正确验证” 我的GET请求验证良好,但POST请求失败 _twitterRestClient = new RestClient("https://ads-api.twitter.com/1") { Authenti

使用Postman,我能够使用Twitter
API
,使用Postman的OAuth 1.0授权,成功地查询和创建定制的受众。然而,当尝试对RestSharp执行相同操作时,我得到了一个未经授权的错误

“未经授权的访问”-“此请求未正确验证”

我的
GET
请求验证良好,但POST请求失败

        _twitterRestClient = new RestClient("https://ads-api.twitter.com/1")
        {
            Authenticator = OAuth1Authenticator.ForProtectedResource(ConsumerKey, ConsumerSecret, AccessToken, AccessSecret)
        };

        var restRequest1 = new RestRequest(string.Format("/accounts/{0}/tailored_audiences", TwitterAccountId), Method.GET);
        //this works and gives me a list of my tailored audiences
        var response1 = _twitterRestClient.Execute(restRequest1);

        var restRequest2 = new RestRequest(string.Format("/accounts/{0}/tailored_audiences?name=SampleAudience2&list_type=EMAIL", TwitterAccountId), Method.POST);
        // this results in an "Unauthorized" status code , and the message {\"code\":\"UNAUTHORIZED_ACCESS\",\"message\":\"This request is not properly authenticated\"}
        var response2 = _twitterRestClient.Execute(restRequest2);

事实证明,这是由于RestSharp OAuth1实现中的一个怪癖造成的。我认为这与这个问题有关-。创建OAuth1签名的一部分涉及收集请求中的所有参数和其他详细信息,然后对其进行散列。如果HTTP方法是POST,那么RestSharp在querystring中不需要参数(这很有意义),而是在POST正文中需要参数。无论如何,如果您显式地添加参数,那么它们将被拾取,OAuth1签名将起作用。(事实证明,如果这些参数在帖子正文中,twitter API就可以工作,所以我不需要显式地将它们添加到查询字符串中)。更新的代码现在可以工作了:

        _twitterRestClient = new RestClient("https://ads-api.twitter.com/1")
        {
            Authenticator = OAuth1Authenticator.ForProtectedResource(ConsumerKey, ConsumerSecret, AccessToken, AccessSecret)
        };

        var restRequest1 = new RestRequest(string.Format("/accounts/{0}/tailored_audiences", TwitterAccountId), Method.GET);
        var response1 = _twitterRestClient.Execute(restRequest1);

        var restRequest2 = new RestRequest(string.Format("/accounts/{0}/tailored_audiences", TwitterAccountId), Method.POST);
        restRequest2.AddParameter("name", "SampleAudience2");
        restRequest2.AddParameter("list_type", "EMAIL");
        var response2 = _twitterRestClient.Execute(restRequest2);

谢谢,它也适用于WooCommerceAPI