DotNetCurry Logo

Secure Web API 2.0 Services using External Authentication like Twitter

Posted by: Suprotim Agarwal , on 8/8/2013, in Category ASP.NET
Views: 29144
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 http://dev.twitter.com/ and create a new Application. Note down the ConsumerKey and ConsumerSecret.

twitter-oauth-settings

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

web-api-external-auth

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

app.UseTwitterAuthentication(
    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.

image

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

authorize-app-twitter

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!

register-twitter-account

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.

logged-in-successful

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:

database-schema

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

identity-provider

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

older-forms-authentication-principal

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.

Conclusion

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)

Was this article worth reading? Share it with fellow developers too. Thanks!
Share on LinkedIn
Share on Google+
Further Reading - Articles You May Like!
Author
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 a new one recently at The Absolutely Awesome jQuery CookBook.

Suprotim has received the prestigious Microsoft MVP award for nine times in a row now. In a professional capacity, he is the CEO of A2Z Knowledge Visuals Pvt Ltd, a digital group that represents premium web sites and digital publications comprising of Professional web, windows, mobile and cloud developers, technical managers, and architects.

Get in touch with him on Twitter @suprotimagarwal, LinkedIn or befriend him on Facebook



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
Hi,
   Thank u Very much For this Useful Information…

<a href="http://www.certificate-attestation.in/">Authentication Services
</a>
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