Twitter oAuth in .Net without Web Login

I was interested in getting a Twitter App together to orchestrate some follows and unfollows and user searches for a personal project. In the past, I’ve used Twitter’s Basic Authentication API to get my Twitter feed, but according to the Twitter API documentation, Basic Auth is going to be unsupported in August of this year. So I figured I might as well get my feet wet with Twitter oAuth authentication.

I came across this article about how to use Twitter oAuth with .Net (via Twitter API documentation) and used the extended oAuth code for my own project.

Unfortunately in all examples of desktop apps that I can find, they all involve opening up Twitter.com in a web browser control to get the user’s PIN for the app. Of course, this makes sense, but I wanted to short circuit this process. I wanted to be able to enter a userid and password and go straight into my account.

Here’s a quick snip of my code in case you’re interested in doing the same. The code uses HTTPWebRequest and HTTPWebResponse to automate the PIN request procedure so a web browser control is not needed.

This code uses Twitter oAuth for .Net from here, which itself extends .Net oAuth from here. The code is probably not complete as I simply took the code snippets from a larger project and as such, some variables may not be declared or initialized properly.

//Assumes these vars are populated before below code.
private string _consumerKey = "";
private string _consumerSecret = "";
private string _userid = "";
private string _password = "";

//These get populated by below code
private string _token="";
private Uri AuthUri = null;
private oAuthTwitter oAuth;
private string _pin = "";

public void authenticate()
{
    oAuth = new oAuthTwitter();
    oAuth.ConsumerKey = _consumerKey;
    oAuth.ConsumerSecret = _consumerSecret;

    Uri AuthUri = new Uri(oAuth.AuthorizationLinkGet());
    _token = HttpUtility.ParseQueryString(AuthUri.Query)["oauth_token"];
    CookieContainer cookies = null;
    string content = getContent(AuthUri.ToString(), null, "", null, ref cookies);
    string authenticity_token = Regex.Match(content, "twttr\\.form_authenticity_token = '([^']+)';", RegexOptions.IgnoreCase).Groups[1].Value;

    string post = ue("authenticity_token", authenticity_token) +
                    "&" + ue("oauth_token", _token) +
                    "&" + ue("session[username_or_email]", _userid) +
                    "&" + ue("session[password]", _password) + "&Allow=allow";

    content = getContent(oAuthTwitter.AUTHORIZE, post, "https://www.twitter.com/", cookies, ref cookies);
    Match m = Regex.Match(content, "oauth_pin\\\">\\s*([0-9]+)", RegexOptions.IgnoreCase);
    _pin = "";
    if (m != null)
    {
        _pin = m.Groups[1].Value;
    }

    oAuth.Token = _token;
    oAuth.AccessTokenGet(_token, _pin);
    if (oAuth.TokenSecret.Length > 0)
    {
        string xml = oAuth.oAuthWebRequest(oAuthTwitter.Method.GET, "http://twitter.com/account/verify_credentials.xml", String.Empty);
    }
}
private string ue(string parm, string val)
{
    return HttpUtility.UrlEncode(parm) + "=" + HttpUtility.UrlEncode(val);
}

public static string getContent(string url, string requestBody, string referrer, CookieContainer cookies, ref CookieContainer retCookies)
{
    ServicePointManager.CertificatePolicy = new trustedCertificatePolicy();
    HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);
    request.Method = (requestBody == null) ? "GET" : "POST";
    request.UserAgent = "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.2.6) Gecko/20100625 Firefox/3.6.6 (.NET CLR 3.5.30729)";
    request.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8";
    request.Referer = referrer;
    request.CookieContainer = cookies;

    if (requestBody != null)
    {
        request.ContentType = "application/x-www-form-urlencoded";
        request.ContentLength = System.Text.Encoding.UTF8.GetByteCount(requestBody);
        Stream requestStream = request.GetRequestStream();
        StreamWriter writer = new StreamWriter(requestStream);
        writer.Write(requestBody);
        writer.Flush();
    }
    HttpWebResponse response = (HttpWebResponse)request.GetResponse();
    Stream stream = response.GetResponseStream();
    StreamReader reader = new StreamReader(stream);
    string content = reader.ReadToEnd();

    CookieContainer rc = new CookieContainer();

    UriBuilder ubuilder = new UriBuilder();
    Uri u = new Uri("https://www.twitter.com");

    rc.SetCookies(u, response.Headers["Set-Cookie"]);
    rc.Add(response.Cookies);
    retCookies = rc;

    return content;
}
You can leave a response, or trackback from your own site.

Leave a Reply