Monday, September 27, 2010

Twitter oAuth SHA1 Digest Class / Webmatrix Helper

*** Update*** For some reason the class wasn't showing up, making this info useless. Fixed.

I've decided to use Twitter's @anywhere Javascript service to integrate Twitter functionality into a website I'm building.

I found it pretty easy to use. I decided to integrate some server side logic once a person logged into my website using Twitter. Knowing that Javascript is pretty easy to spoof, I wanted to explore ways of not taking a given user's Twitter login for granted. I found this cryptic paragraph in the @anywhere documentation listed above.

Once the user has authorized the host site, Anywhere will set a cookie named "twitter_anywhere_identity" that contains the id of the logged in user. You can read this on the server side to learn the user's ID. The format of the cookie is:

user_id:signature

When reading the cookie on the server, you should use the signature to verify that this information has come from Twitter. Calculate the signature by appending the given user_id to your OAuth consumer secret and creating a SHA1 hex digest. If this matches the signature in the identity cookie the user ID is verified. For example, in Ruby:

Digest::SHA1.hexdigest(user_id + consumer_secret)

Ut Oh. I know Twitter tends to not have a lot of examples in .Net floating around. After Googling for a bit I found this excellent article on .Net and SHA1 Interop by Jonathan Cogley-

http://authors.aspalliance.com/thycotic/articles/view.aspx?id=2

After doing a few minor tweeks to Jonathan's base code (name space change from .Net 1.1), I present to you a Twitter oAuth SHA1 Digest class




Usage-

The above class will work with any flavor of .Net. If you want to use the above class as a Webmatrix helper, create a class file, rename it TweetSHADigest.cs, paste over the generated code in the file with the above code. The class file should be in a folder called App_Code.

Once Twitter has made a call back to your web site, you can verify that the cookie set came from twitter like so. You will need your web application's Twitter OAuth consumer secret.




No comments: