„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

Learn more about our team.

5 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
  3. When I press the button to allow the application , I get this error
    Erreur du serveur DANS L’application ‘/’.

    La Valeur etait trop grande ous trop petite Pour Un Int32.

    Description: Une exception non Gerée S’est produite au moment de l’exécution de de la personal property actuelle Web. Contrôlez la trace de la pile verser Plus d’informations sur l’Erreur et fils origine de dans le code.

    Détails de l’exception: System.OverflowException: La Valeur etait trop grande ous trop petite Pour Un Int32.

    Erreur source:

    Ligne 49: / / Étape 3 – Remplacer le jeton de demande pour un jeton d’accès
    Ligne 50: service de TwitterService = new TwitterService (_consumerKey, _consumerSecret);
    Ligne 51: OAuthAccessToken accessToken = service.GetAccessToken (requestToken, oauth_verifier);
    Ligne 52: / / Étape 4 – authentifie l’utilisateur à l’aide du jeton d’accès
    Ligne 53: service.AuthenticateWith (accessToken.Token, accessToken.TokenSecret);
    PS: la ligne 51 est de couleur
    i need help please

    Reply
  4. Very Usefull article. But I want to know what is the use of AuthorizeCallback ? How can we get oauth_token and oauth_verifier values? I want to get User name and user id . How can we do this ?

    Reply
    • The AuthorizeCallback will be invoked from Twitter – this is the callback after a successful authentication on Twitter. With the OAuth Token you can reach to Twitter again to get Screenname and so on.

      Reply

Comment on this post

Recent Posts

  • image1929-570x143_thumb.png
    Create and validate own Json-Web-Tokens (JWTs)

    If you are interested in web authentication you probably have heard about JSON Web tokens (JWT). What is a JWT? Maybe I’m not using the correct security termination but however: JWTs are used to exchange claims between two systems. For example: You want to log on to a service (like Facebook, Twitter, etc.) and want […]

  • Micro-Optimization: how to shrink or „embed“ pictures

      I’m currently working on the “CodeInside Dashboard” and since the page structure isn’t that difficult it should be possible to fulfill all of Google Pagespeed or Yahoos YSlow recommendations. One of the rules was to optimize the 4 PNGs that are embedded on the page.   Before – without optimization: Below you can see […]

  • image1979-570x194.png
    Move to Windows Azure – VMs, Word Press Migration, DNS changes

    Since mid January this blogs runs on a WordPress installation in an Azure VM. Because I always thought that the subject is quite complicated this blogpost offers a view behind the scenes. Why this move? So far this blog (both German and English Version) runs on a hoster somewhere in Germany. The main problem with this […]

  • Windows Azure Active Directory – CRUD for users and groups

      Windows Azure Active Directory? If you are not informed about the subject I recommend you to have a look on this Azure Info site. Which resources are there? The Azure AD contains the following entities: - Users - Groups - Contacts - Roles Access to the directory or on the “directory graph” Although the […]

  • Introduction into SignalR 2.0 & Azure Website Websockets

      SignalR is an Open Source Framework for Real Time WebApps. The main problem with Real-Time in the web is the canal between Browser and Server. If you never had to deal with SignalR and this problem before here is a brief introduction:   The problem Traditionally the browser initiates the request to the server […]

Support us