Thursday, November 18, 2010

Twitter OAuth - How To

Step 1:
Register your application. Don't know if you've to Callback URL field but I just assigned to a HTML page that contain very little information.

Step 2:
Get Twitterizer library from here

Step 3:
Use the following code to get the Twitter OAuth token. I used a session to store it but essentially, as long as you store it either using a Cookie, ViewState, Session, row on the DB, that's totally up to you.

OAuthTokenResponse oatResponse = OAuthUtility.GetRequestToken(CONSUMERKEY, CONSUMERSECRET, HttpContext.Current.Request.Url.AbsoluteUri);

if ((Request.QueryString["oauth_token"] == null) && (Session["tweetOAuthToken"] == null))
Uri uri = OAuthUtility.BuildAuthorizationUri(oatResponse.Token);
oatResponse = OAuthUtility.GetAccessToken(CONSUMERKEY, CONSUMERSECRET, Request.QueryString["oauth_token"], Request.QueryString["oauth_verifier"]);

//Add to Session that will expire in 24 hours
OAuthTokens oAuthToken = new OAuthTokens();
oAuthToken.AccessToken = oatResponse.Token;
oAuthToken.AccessTokenSecret = oatResponse.TokenSecret;
oAuthToken.ConsumerKey = CONSUMERKEY;
oAuthToken.ConsumerSecret = CONSUMERSECRET;
Session.Add("tweetOAuthToken", oAuthToken);
Session.Timeout = 1440;


NOTES:The consumer token and secret is obtained when you register your application and there is definately a requirement to tidy up this code but it works