Thursday, February 16, 2012

DotnetOpenAuth & Twitter

This is the first in a series of posts about using DotnetOpenAuth to provide authentication from external services. Today, we're talking about Twitter.

The first thing you need to do is to create an app with Twitter. Visit https://dev.twitter.com/apps, login, and then click "Create a new application". Fill out the simple form. Use any valid website for your site and for your callback URL - preferrably something for your specific organization or project, but if you don't have anything, just put down anything. The important thing is to make sure you fill it all out. After your app is created, you will see a details screen that includes a section of "OAuth settings". The import items for step 2 are the Consumer Key and the Consumer Secret.

Next, you need to include the Consumer Key/Secret into your .Net application. That means including the relevant data as part of your Web.config. Something like this (note that the key/secret here are for the DotNetOpenAuth sample test project; it'll look pretty silly if you forget to replace these with the values of your actual project:
<appSettings>
 <!-- Fill in your various consumer keys and secrets here to make the sample work. -->
 <!-- You must get these values by signing up with each individual service provider. -->
 <!-- Twitter sign-up: https://twitter.com/oauth_clients -->
 <add key="twitterConsumerKey" value="eRJd2AMcOnGqDOtF3IrBQ" />
        <add key="twitterConsumerSecret" value="iTijQWFOSDokpkVIPnlLbdmf3wPZgUVqktXKASg0QjM" />
  </appSettings>

Finally, we can get to coding the app. Your first step is to download the DotNetOpenAuth package. There are several different versions available, but at the time of this article the best one (read: only one I could make work for Twitter, Facebook, and OpenID) is version 3.5.0.x. Grab this, and play around with it as much as you like. Or just yank some of the dll's and move on with doing your actual project. The ones you are interested in are DotNetOpenAuth.dll and DotNetOpenAuth.ApplicationBlock.dll. They can both be found in \Samples\OAuthClient\bin\ of the repository you downloaded. Load these in as project references to your .Net app. My experience is that this works best if you place the dlls into the \bin\ folder of your app and then right-click on the project in Visual Studio to add the references.

Once you have the references set up, design the frontend. Set it up however you would like, but the key is to provide some kind of link that will prompt people to sign-in via Twitter. You can make your own, or use one of the ones that Twitter provides for you. It is the clicking of that link to which you want to attach some processing.

On the backend of your app, start off by including everything you need. Cheat by replicating the includes from the sample project (while you may not need all of them, it's easiest to start with everything and then remove the ones you know you do not need):
using System;
 using System.Collections.Generic;
 using System.Configuration;
 using System.Linq;
 using System.Web;
 using System.Web.Security;
 using System.Web.UI;
 using System.Web.UI.WebControls;
 using System.Xml.Linq;
 using System.Xml.XPath;
 using DotNetOpenAuth.ApplicationBlock;
 using DotNetOpenAuth.OAuth;

Next, include the actual login stuff in the page load:
if ((Request["openid_identifier"] == "http://twitter.com/")|| ((Request["oauth_token"] != null) && (Request["oauth_token"].Length > 1)))
{
    if (TwitterConsumer.IsTwitterConsumerConfigured)
    {
        if (IsPostBack)
        { TwitterConsumer.StartSignInWithTwitter(true).Send(); }
        else
        {
            string screenName;
            int userId;
            if (TwitterConsumer.TryFinishSignInWithTwitter(out screenName, out userId))
            {
                //userId is now a unique numeric id for the user
                //screenName is now their Twitter username

                //use these values to do whatever you want
            }
        }
    }
}

After that, you're done. Cheers, you now have their information from Twitter. Use it however you like!

No comments:

Post a Comment