Secure Web API 2.0 Services using External Authentication like Twitter

Posted by: Suprotim Agarwal , on 8/8/2013, in Category ASP.NET
Views: 40243
Abstract: A quick peek at the new and shiny Security model in the upcoming ASP.NET vNext. We use the new Claims Based Authentication system and create a ASP.NET Web API 2.0 sample app that uses Twitter as the external Authentication Service.

The upcoming release of ASP.NET overhauls the Security mechanism completely. As a part of the revamp, the underlying Forms Authentication mechanism is being replaced by a Claims based Authentication model. Dominick Baier has a nice comparison of the current Forms based Auth vs. the upcoming Claims based auth here. In a nutshell, the new Auth Mechanism can store a lot of Authentication and Authorization information and do it better in terms for extensibility and security. Dominick’s article was written when things were pretty raw and you had to manually configure the new mechanism. However with Visual Studio 2013 Preview, a lot of the plumbing is done by the Project templates. Though things might change some more by the time VS 2013 is GA, things are pretty usable as of now.


Beauty of the new system is unless someone told you explicitly, you wouldn’t realize the change under the covers. We’ll try to walk parallel paths in VS 2013 and VS 2012 and see the differences.

Note: The Web Team released a tools refresh for VS 2013 Preview also. I recommend getting the update as it has some changes to the Identity Foundation libraries that have gone from Alpha to Beta (More info here).

Setting up Twitter Auth for your Web API 2.0 Application

Before you get started, you have to get CustomerKey and CustomerSecret from Twitter. Login to and create a new Application. Note down the ConsumerKey and ConsumerSecret.


Also in the settings Tab, there is an option to Enable Twitter Authentication. Be sure to check it and save the settings. Finally you should setup a ‘Callback Url’ as shown belowenable-sign-in-with-twitter

Without the Callback URL and the ‘Allow Sign in’ checked It’s unchecked running the app will give you a 401.

Building a ASP.NET Sample

Now let’s get started with our App.

1. Create a new Web Project and Select the SPA Template



2. Once the project is created, open Startup.Auth.cs in the App_Start folder and uncomment the app.UserTwitterAuthentication line. Copy over the consumerKey and consumerSecret from your Twitter App. The final statement should look as follows

    consumerKey: "FcO5sPaxkwarRu6Qtbvuw",
    consumerSecret: "PF5aivnyFZggSRqXFlnKPH65QT1st4Y2nqW7dRzlg");

3. That’s pretty much all you need to do to setup External Authentication. If you look at Startup.Auth.cs closely, you’ll see there is a commented out setting for Facebook and Google as well, so if you set up an appropriate App

4. Run the Application. Notice apart from the standard log in, you’ll see Twitter enabled for ‘Log in using another service’. If you provide connection details for other service providers like Facebook, Google or Microsoft, each of those options will get enabled.


5. Click on the Twitter button to Authenticate with Twitter. This will navigate the app to a Login page hosted by Twitter. Essentially your users are not giving you their passwords (which is almost universally a good thing). Note how Twitter identifies your App and tells the user what permissions your app is asking for (or what it can and cannot do after you authorize it).


6. Once the end user Provides their Twitter Credentials and Signs in, the application will redirect to the Callback URL that was provided. Note: You can click on the ‘Remember me’ check box here, it works now and you don’t have to re-authorize every time you restart the application!


7.  For first time Login, the Auth Mechanism will ask you to choose a username to link up your Twitter account with in this application and Signup process will be complete.


Readily Apparent Changes or Differences

1. Close the browser in which the app was running and restart the application. On the Login page, click on Twitter button if you had selected Save login information in step 5, you will see Twitter recognizes your app and redirects you to it using Saved Credentials. This flow is broken in the older version of the Auth API.

2. Next when we open the Database, we’ll see the Authentication related tables are now cleaner and more uniformly named as seen below:


3. The IPrincipal entity has also changed significantly (this is actually the crux of the changes). If we put a breakpoint in any of the controller methods and then watch the “User” object in the context, we’ll see the following


The User object is now an instance of the System.Security.Claims.ClaimsPrincipal as opposed to the earlier System.Security.RolePrincipal.


4. Auth is now an OWIN compliant module. This is a subtle but very significant architectural change that is sweeping the entire ASP.NET stack – Conformance with the OWIN spec. The new Authentication Module is written as an OWIN component so you can expect it to be usable in other hosting scenarios like Self Hosted Web APIs.

5. Finally, it’s worth mentioning the use of Bearer tokens throughout, even in case where you are storing user name and credentials within the App instead of using External Login providers. What this means is, once authorized instead of using credentials, the App uses Bearer tokens to present it’s claims towards access to a particular resources. The Web Application validates this claim with the Auth component and if Auth server approves grants access to the protected resource.


The upcoming version of ASP.NET is going to see a major overhaul of the Authentication stack. Today we took a sneak peek at how things have changed for the better under the covers.

Download the entire source code of this article (Github)

This article has been editorially reviewed by Suprotim Agarwal.

Absolutely Awesome Book on C# and .NET

C# and .NET have been around for a very long time, but their constant growth means there’s always more to learn.

We at DotNetCurry are very excited to announce The Absolutely Awesome Book on C# and .NET. This is a 500 pages concise technical eBook available in PDF, ePub (iPad), and Mobi (Kindle).

Organized around concepts, this Book aims to provide a concise, yet solid foundation in C# and .NET, covering C# 6.0, C# 7.0 and .NET Core, with chapters on the latest .NET Core 3.0, .NET Standard and C# 8.0 (final release) too. Use these concepts to deepen your existing knowledge of C# and .NET, to have a solid grasp of the latest in C# and .NET OR to crack your next .NET Interview.

Click here to Explore the Table of Contents or Download Sample Chapters!

What Others Are Reading!
Was this article worth reading? Share it with fellow developers too. Thanks!
Share on LinkedIn
Share on Google+

Suprotim Agarwal, MCSD, MCAD, MCDBA, MCSE, is the founder of DotNetCurry, DNC Magazine for Developers, SQLServerCurry and DevCurry. He has also authored a couple of books 51 Recipes using jQuery with ASP.NET Controls and The Absolutely Awesome jQuery CookBook.

Suprotim has received the prestigious Microsoft MVP award for Sixteen consecutive years. In a professional capacity, he is the CEO of A2Z Knowledge Visuals Pvt Ltd, a digital group that offers Digital Marketing and Branding services to businesses, both in a start-up and enterprise environment.

Get in touch with him on Twitter @suprotimagarwal or at LinkedIn

Page copy protected against web site content infringement 	by Copyscape

Feedback - Leave us some adulation, criticism and everything in between!
Comment posted by Authentication Services on Wednesday, November 6, 2013 1:22 AM
   Thank u Very much For this Useful Information…

<a href="">Authentication Services
Comment posted by Paul on Tuesday, December 3, 2013 4:15 PM
How can I use this mechanism when I have mobile App on mobile platform and .Net web service that should allow Twitter/Facebook registration.
I assume tha mobile App should send token delivered from provider (twiter/FB) and then web service platform can request user details from provider...

The thing is that it is not clear to me how to use mechanism described above for that particular case