Twitter oAuth for version 1.1

Recently needed to rehash some code on an existing twitter based application. The app was getting feeds and tweets. Before, all it needed was to include the twitter account credentials in order to be authenticated. Straight and simple. But twitter modified their APIs to support oAuth. So now, one will not need to register a twitter account, but to register an application to get credentials.

These will be the basic steps:

  1. Get the app oAuth certified and get an oAuth ID that Twitter’s APIs will honor
  2. Generate some more values based on Twitter’s documentation
  3. Submit these values in proper order either as a post or a get, as parameters

So I came up with a TwitterHelper object that can help me out. The oAuth part was pretty straightforward, but the ID generation was the tricky bit. Although there was enough documentation(that I was forced to read), examples for the .net world; C# were scarce. This was the first time I encountered a requirement to “percent encode” a string. J

Okay, so the first part is getting oAuth keys, there are pages for that, you can google that on bing.

// oauth application keys


var oauth_token = “your oauth token”;


var oauth_token_secret = “your oauth token secret”;


var oauth_consumer_key = “your consumer key”;


var oauth_consumer_secret = “your consumer secret”;


// oauth implementation details


var oauth_version = “1.0”;


var oauth_signature_method = “HMAC-SHA1”;

 

These values will be generated by Twitter for you in their dev site. There is a tool there.

Next you will need to create the other parameters needed like the nonce, timestamp and other values

// unique request details


var oauth_nonce = Convert.ToBase64String(


new System.Text.ASCIIEncoding().GetBytes(DateTime.Now.Ticks.ToString()));


var timeSpan = DateTime.UtcNow

new
DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc);


var oauth_timestamp = Convert.ToInt64(timeSpan.TotalSeconds).ToString();

 

These details are unique per user, and per session, so you will need to generate these at runtime.

Now that you have the needed parameters, you will need to combine these to generate a header for your get or post

//setup the parameters that we will be putting in the authorization


var authorizationParameters = new
List<KeyValuePair<string, string>>() {


new
KeyValuePair<string, string>(“oauth_consumer_key”, oauth_consumer_key),


new
KeyValuePair<string, string>(“oauth_nonce”,oauth_nonce),


new
KeyValuePair<string, string>(“oauth_signature_method”,oauth_signature_method),


new
KeyValuePair<string, string>(“oauth_timestamp”,oauth_timestamp),


new
KeyValuePair<string, string>(“oauth_token”,oauth_token),


new
KeyValuePair<string, string>(“oauth_version”,oauth_version)

};

Then you combine the parameters (or sort them) in alphabetical order.

var allParameters = authorizationParameters.Union(RequestParameters).OrderBy(tmp => tmp.Key);

why alphabetical? Check it here: https://dev.twitter.com/docs/auth/creating-signature

then you compose a base string that will be “percent encoded” so you can use it as part of the header

var baseString = string.Join(“&”, allParameters.Select(p => string.Format(“{0}={1}”, p.Key, Uri.EscapeDataString(p.Value))));

 

Then we do the percent encoding bit

baseString = string.Format(“{0}&{1}&{2}”, Method, Uri.EscapeDataString(ResourceUrl), Uri.EscapeDataString(baseString));

 


var compositeKey = string.Format(“{0}&{1}”, Uri.EscapeDataString(oauth_consumer_secret), Uri.EscapeDataString(oauth_token_secret));

 

You now have the ability to create a signature that Twitter will honor

string oauth_signature = null;


using (System.Security.Cryptography.HMACSHA1 hasher = new System.Security.Cryptography.HMACSHA1(System.Text.ASCIIEncoding.ASCII.GetBytes(compositeKey)))

{

oauth_signature = Convert.ToBase64String(

hasher.ComputeHash(System.Text.ASCIIEncoding.ASCII.GetBytes(baseString)));

}

 

As mentioned above, these values need to be included in the request’s header


// create the request header


var headerFormat = “OAuth oauth_nonce=\”{0}\”, oauth_signature_method=\”{1}\”, “ +


“oauth_timestamp=\”{2}\”, oauth_consumer_key=\”{3}\”, “ +


“oauth_token=\”{4}\”, oauth_signature=\”{5}\”, “ +


“oauth_version=\”{6}\””;

 


//get the actual string version of the auth header and its values


var authHeader = string.Format(headerFormat,


Uri.EscapeDataString(oauth_nonce),


Uri.EscapeDataString(oauth_signature_method),


Uri.EscapeDataString(oauth_timestamp),


Uri.EscapeDataString(oauth_consumer_key),


Uri.EscapeDataString(oauth_token),


Uri.EscapeDataString(oauth_signature),


Uri.EscapeDataString(oauth_version)

);

 

Then we now add the parameters to the request


var parameterString = string.Join(“&”, RequestParameters.Select(p => string.Format(“{0}={1}”, p.Key, Uri.EscapeDataString(p.Value))));

ResourceUrl += “?” + parameterString;

Then trigger the request

//create our request

System.Net.HttpWebRequest request = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(ResourceUrl);

 


//set our info

request.Headers.Add(“Authorization”, authHeader);

request.Method = Method;

request.ContentType = “application/x-www-form-urlencoded”;

request.PreAuthenticate = true;

request.AllowWriteStreamBuffering = true;


//get the response and return the result from the stream


var response = (System.Net.HttpWebResponse)request.GetResponse();


var reader = new System.IO.StreamReader(response.GetResponseStream());

This will now give you a StreamReader J

 

All these code, I put inside a function

private
static
StreamReader TwitterCall(string Method, string ResourceUrl, IEnumerable<KeyValuePair<string, string>> RequestParameters)

that is called by


public
static
StreamReader TwitterCallGet(string ResourceUrl, IEnumerable<KeyValuePair<string, string>> RequestParameters)

{


return TwitterCall(“GET”, ResourceUrl, RequestParameters);

}

 


public
static
StreamReader TwitterCallPost(string ResourceUrl, IEnumerable<KeyValuePair<string, string>> RequestParameters)

{


return TwitterCall(“POST”, ResourceUrl, RequestParameters);

}

Which is in turn, called by the main code as

StreamReader resulta = TwitterHelper.TwitterCallPost(_config.StreamingURL, new KeyValuePair<string, string>[] { new KeyValuePair<String, String>(“track”, _config.Parameters) });

 

There you go. I hope you can figure out how to use this. J

 

 

 

 

 

 

 

Advertisements
This entry was posted in Computers and Internet. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s