TAGS :Viewed: 11 - Published at: a few seconds ago

[ OAuth1 Authentication in RestSharp for Twitter API GET and POST methods ]

Using Postman I'm successfully able to query and create tailored audiences using the Twitter API, using Postman's OAuth 1.0 Authorization. However when trying to do the same with RestSharp I get an Unauthorized error.

"UNAUTHORIZED_ACCESS" - "This request is not properly authenticated".

My GET request authenticates fine, but the POST request fails.

        _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);

Answer 1


Turns out this is due to a quirk in RestSharp OAuth1 implementation. I think its related to this issue - https://www.bountysource.com/issues/30416961-oauth1-not-specifing-parameter-type . Part of creating an OAuth1 signature involves gathering all the parameters in the request and other details and then hashing it all. It looks like when the HTTP Method is a POST, then RestSharp is not expecting parameters in the querystring (which makes sense), its expecting them in the post body. Anyhow if you add parameters explicitly then they are picked up and the OAuth1 signing works. (Turns out the twitter API works if these params are in the post body, so I didn't need to explicitly add them to the query string). Updated code that now works:

        _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);