25 April 2012 ASP.NET, Twitter CI Team

 

“Sign in with Twitter” is a popular practice to authenticate the users on your website. One advantage compared to an own registration is the lower inhibition for the user. But on the other hand Twitter doesn’t fess up with all the information’s and you will get into a kind of addiction. At the end everyone has to decide it by them self. The question is: How can I integrate the Twitter Login into my website?

Twitter Login – Oauth

The base is the OAuth protocol for the authentication. The application isn’t able to see secure information’s like keywords. More background information’s here.

TweetSharp – 10 minutes guide to Twitter Login

At least the OAuth protocol is a little bit “difficult”. There is a big library in the .NET environment which is able to understand both OAuth and OpenID: DotNetOpenAuth. But the library is very extensive and heavy. So here is my recommendation: TweetSharp!

Step 1: Take it from NuGet

Of course TweetSharp is also a NuGet package:

image1490

Step 2: register the Twitter App

On the Developer Side of Twitter you are able to adjust new apps. For our Dev-version the following information’s are enough.

Important: enter the same information’s into WebSite and Callback URL – otherwise there are going to be some problems. We choose 127.0.0.1 – localhost. You are able to fit it on the right URL later into the application.

image

The most important information’s:image

We need the Consumer Key and the Consumer Secret soon.

Note: There are several “authorities” to be set on the Access level. At the moment it is only possible to read the Tweets but it is not possible to write them with the application. So the Twitter App is for registration only and the user is going to be informed about it on the login-page.

Step 3: Auth Controller

The code from Auth Controller is from the Doku on TweetSharp and I only changed a few things.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;
using TweetSharp;

namespace OAuthSignInWithTwitter.Controllers
{
    public class AuthController : Controller
    {
        private string _consumerKey = "BOgMSVFOOOBARRRRR7QOB9Yw";
        private string _consumerSecret = "lRCbswKMKxFOOOBARRRRR2eL20X5uWG1FOOOBARRRRRjl3MM323pE8";

        public ActionResult Authorize()
        {
            // Step 1 - Retrieve an OAuth Request Token
            TwitterService service = new TwitterService(_consumerKey, _consumerSecret);

            var url = Url.Action("AuthorizeCallback", "Auth", null, "http");
            // This is the registered callback URL
            OAuthRequestToken requestToken = service.GetRequestToken(url);

            // Step 2 - Redirect to the OAuth Authorization URL
            Uri uri = service.GetAuthorizationUri(requestToken);
            return new RedirectResult(uri.ToString(), false /*permanent*/);
        }

        // This URL is registered as the application's callback at http://dev.twitter.com
        public ActionResult AuthorizeCallback(string oauth_token, string oauth_verifier)
        {
            var requestToken = new OAuthRequestToken { Token = oauth_token };

            // Step 3 - Exchange the Request Token for an Access Token
            TwitterService service = new TwitterService(_consumerKey, _consumerSecret);
            OAuthAccessToken accessToken = service.GetAccessToken(requestToken, oauth_verifier);

            // Step 4 - User authenticates using the Access Token
            service.AuthenticateWith(accessToken.Token, accessToken.TokenSecret);
            TwitterUser user = service.VerifyCredentials();

            FormsAuthentication.SetAuthCookie(user.ScreenName, false);

            return RedirectToAction("Index", "Home");
        }
    }
}

Between Step 1 and 2 we create the main Callback-URL. In this Callback we use the FormsAuthentication and set the Cookie so also the ASP.NET engine will know that we are logged in.

Step 4: UI modification

In the _Layout.cshtml

  
<div id="title">
                <h1>My MVC Application</h1>
            </div>
            <div id="logindisplay">
                @if(this.Request.IsAuthenticated)
                {
                    <span>@@@HttpContext.Current.User.Identity.Name</span>
                }
                else
                {
                    @Html.ActionLink("Sign in with Twitter", "Authorize", "Auth");
                }
            </div>

Either the user is logged in via ForumsAuthentication or we show the Link to the Authorize Methode.

Result:

image

image

image

Additional we can access on several Twitter attributes of the user. That’s it about the authentication. Not that difficult at all. If you want to use more futures for example sending Tweets has to keep in mind the AccessToken from the Callback.

On my Project KnowYourStack.com I use a “Tinkerversion” via the DotNetOpenID Project – it works almost equal but it is a little bit more complicated so I recommend TweetSharp for this easy business.