OAuth for Twitter Search and Streaming API


#1

I’ve been able to get OAuth working for both searching and streaming tweets but it only seems to work for a single word (q=football, track=football). If I put in multiple words in my GET and POST, I get an Unauthorized error. Seems weird as I am encoding it. Has anyone had a similar problem? Happy to share the C# code if you think it will help.


#2

Please share some code as it will be easier to assist. What library are you using?


#3

It works when you search a single word, fails when you search multiple words.

Error:
The remote server returned an error: (401) Unauthorized.-2146233079 at System.Net.HttpWebRequest.GetResponse() at Twitter.d__0.MoveNext()

OAuth Code for Search API:
try
{
string searchTerm = searchTermTextBox.Text + “-filter:retweets” + “&result_type=recent”;
string url = ConfigurationManager.AppSettings[“TwitterUrl”] + “?q=” + searchTerm;

        string oauth_token = ConfigurationManager.AppSettings["AccessToken"];
        string oauth_consumer_key = ConfigurationManager.AppSettings["ConsumerKey"];

        string oauth_version = "1.0";
        string oauth_signature_method = "HMAC-SHA1";
        var timeSpan = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc);
        string oauth_timestamp = Convert.ToInt64(timeSpan.TotalSeconds).ToString();
        string oauth_nonce = Convert.ToBase64String(new ASCIIEncoding().GetBytes(DateTime.Now.Ticks.ToString()));

        SortedDictionary<string, string> sd = new SortedDictionary<string, string>();

        sd.Add("q", searchTerm);
        sd.Add("oauth_version", oauth_version);
        sd.Add("oauth_consumer_key", oauth_consumer_key);
        sd.Add("oauth_nonce", oauth_nonce);
        sd.Add("oauth_signature_method", oauth_signature_method);
        sd.Add("oauth_timestamp", oauth_timestamp);
        sd.Add("oauth_token", oauth_token);

        //Build the signature string
        string baseString = String.Empty;
        baseString += "GET" + "&";
        baseString += Uri.EscapeDataString(ConfigurationManager.AppSettings["TwitterUrl"]) + "&";

        foreach (KeyValuePair<string, string> entry in sd)
        {
            baseString += Uri.EscapeDataString(entry.Key +
                "=" + entry.Value + "&");
        }
        baseString = baseString.Substring(0, baseString.Length - 3);

        //Build the signing key
        string oauth_token_secret = ConfigurationManager.AppSettings["AccessTokenSecret"];
        string oauth_consumer_secret = ConfigurationManager.AppSettings["ConsumerSecret"];

        string signingKey = Uri.EscapeDataString(oauth_consumer_secret) + "&" + Uri.EscapeDataString(oauth_token_secret);

        //Sign the request
        HMACSHA1 hasher = new HMACSHA1(new ASCIIEncoding().GetBytes(signingKey));
        string signatureString = Convert.ToBase64String(hasher.ComputeHash(new ASCIIEncoding().GetBytes(baseString)));

        ServicePointManager.Expect100Continue = false;

        string authorizationHeaderParams = String.Empty;
        authorizationHeaderParams += "OAuth ";
        authorizationHeaderParams += "oauth_nonce=" + "\"" + Uri.EscapeDataString(oauth_nonce) + "\",";
        authorizationHeaderParams += "oauth_signature_method=" + "\"" + Uri.EscapeDataString(oauth_signature_method) + "\",";
        authorizationHeaderParams += "oauth_timestamp=" + "\"" + Uri.EscapeDataString(oauth_timestamp) + "\",";
        authorizationHeaderParams += "oauth_consumer_key=" + "\"" + Uri.EscapeDataString(oauth_consumer_key) + "\",";
        authorizationHeaderParams += "oauth_token=" + "\"" + Uri.EscapeDataString(oauth_token) + "\",";
        authorizationHeaderParams += "oauth_signature=" + "\"" + Uri.EscapeDataString(signatureString) + "\",";
        authorizationHeaderParams += "oauth_version=" + "\"" + Uri.EscapeDataString(oauth_version) + "\"";

        WebRequest request = WebRequest.Create(url);
        request.Method = "GET";
        request.ContentType = "application/x-www-form-urlencoded";
        request.Headers.Add("Authorization", authorizationHeaderParams);

        WebResponse response;

        using (response = request.GetResponse())
        {
            using (Stream stream = response.GetResponseStream())
            {
                using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
                {
                       //do something
                }
            }
        }
    }
    catch (Exception ex)
    {
         //log exception
    }

#5

What’s the exact query string? Can you reproduce using twurl?


#6

Ok, it turns out it is a URL encoding issue.

I needed to do Uri.EscapeDataString() for searchTermTextBox.Text.

But now when I go to https://apps.twitter.com it seems I am no longer authorized. Web page reads “Not authorized to use this endpoint.” Was my account disabled due to too many failed attempts?