„Sign in with Twitter“ for your own ASP.NET WebApp

image1489-570x194.png

 

“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.

If you enjoyed this post, please consider leaving a comment or subscribing to the RSS feed to have future articles delivered to your feed reader.

About the author

Written by Code Inside Team

Learn more about our team.

2 Responses

  1. Thank you so much for just getting to the point. A lot of the other tutorials were all about the SimpleMembershipProvider which is very limited. I just wanted to know the basics and your blog post was perfect. Thanks again.

    Reply
  2. Thank you very much, easy to follow and does the job !!

    Reply

Comment on this post

Recent Posts

  • Windows Phone SDK & „System“-Icons

      Although the Metro Design focuses a lot on Typography Icons are still quite important. If you install Windows Phone SDK you will receive 36 Icons. You can find them here: C:\Program Files (x86)\Microsoft SDKs\Windows Phone\v8.0\Icons Unfortunately many Icons you might know from the common applications are not integrated. Pedro Lamas extracted 99 additional Icons ...

  • image1830-570x194.png
    How can I figure out if my ADFS 2.0 works?

      I was working with ADFS 2.0 (“Active Directory Federation Services”) for a while when this simple question crossed my mind: How can I figure out if the connection between ADFS and AD “works”? Here is a simple test… What is ADFS? If you need some “position of trusts” beneath the AD-boarders you choose an ...

  • Subdomain vs. Subdirectory

      Better blog.mydomain.com or mydomain.com/blog? Good question! If got asked this question again via Twitter on the weekend so therefore I decide to share my experiences:   Choose a subdomain, if…. - You plan to offer “different services” which are “logical separated” on one domain - You are able to influence the subdomains without much ...

  • image1792-450x194.png
    Guide to Claim-Based Identity with the Access Control Service

    Microsoft published a free PDF about Claim-based Identity, Access Control Service and how to connect it to the remaining Microsoft world (Sharepoint, ADFS, Azure): Download-Link or MSDN Link I found the announcement today on the blog of Vittorio Bertocci. More information’s? If you want to get deeper into the subject you should risk a look ...

  • image1783-570x194.png
    Windows Azure Websites – Logging & ErrorHandling

    The Azure Websites are easy to handle but still it doesn’t take much effort to add new instances. But how should I react if an error appears? Azure Website Configuration At the adjustments of Azure Websites you will find three diagnostic-tools: · Detailed Error Logging – Turn on detailed error logging to capture all errors ...

Support us