Question

I have been struggling for the last 4 hours trying to get this to work and nothing will work. I've been searching high and low for examples but everything I tried failed.

This is not the first time I am implementing oAuth (I have successfully implemented it for Google Drive and Dropbox) but I can't get the Access Token to use for the Twitter API.

I can do a successful request to get the request token (and secret) and redirect the user to the Twitter website. Once the user has authorized my app, my callback url is hit and I retrieve the verifier.

Now I am supposed to send the verifier and exchange it for the access token (and secret).

However my request to do that always return a 401 Unauthorized error. I have tried so many things that I don't know what else to try. The code for the request is the following:

    Uri uri = new Uri("https://api.twitter.com/oauth/access_token");

    OAuth.OAuthBase oAuth = new OAuth.OAuthBase();
    String nonce = oAuth.GenerateNonce();
    String timestamp = oAuth.GenerateTimeStamp();
    String parameters = "";
    String normalizedUrl = "";
    String signature = oAuth.GenerateSignature(uri, _consumerKey, _ConsumerSecret, requestToken, requestTokenSecret, "POST", timestamp, nonce, OAuth.OAuthBase.SignatureTypes.HMACSHA1, out normalizedUrl, out parameters);

    StringBuilder authHeader = new StringBuilder();
    authHeader.AppendFormat("oauth_token=\"{0}\", ", requestToken);
    authHeader.AppendFormat("oauth_consumer_key=\"{0}\", ", _consumerKey);
    authHeader.AppendFormat("oauth_nonce=\"{0}\", ", nonce);
    authHeader.AppendFormat("oauth_timestamp=\"{0}\", ", timestamp);
    authHeader.AppendFormat("oauth_signature_method=\"{0}\", ", "HMAC-SHA1");
    authHeader.AppendFormat("oauth_version=\"{0}\", ", "1.0");
    authHeader.AppendFormat("oauth_signature=\"{0}\"", Uri.EscapeDataString(signature));

    ServicePointManager.Expect100Continue = false;

    WebRequest request = HttpWebRequest.Create(uri);
    request.Method = WebRequestMethods.Http.Post;
    request.ContentType = "application/x-www-form-urlencoded";
    request.Headers.Add("Authorization", "OAuth " + authHeader.ToString());

    using (StreamWriter sw = new StreamWriter(request.GetRequestStream()))
    {
        sw.WriteLine("oauth_verifier=" + verifier);
    }

    WebResponse response = request.GetResponse();

With requestToken and requestTokenSecret being the tokens I received after the first request.

The oAuth helper class to generate the signature works fine, I have been using it successfully for a while.

What's wrong with that request, that it always give me a 401?

Thanks

Was it helpful?

Solution

Ok so as much as I'd like to know why this was not working, I ended up using Tweetsharp and I had things done in a matter of minutes.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top