Step By Step ASP.NET Identity with Twitter OAuth

Introduction

In this Article, we are going to learn how to implement Twitter Oauth service with ASP.NET MVC 5 application.

The process of each OAuth provider is different as we saw on Facebook, the Facebook provide appId and appSecret and in same way Google provide ClientId and ClientSecret but the way you need to register you application for using this services are totally different from each other, In this fast growing world most of application requires this kind of Authentication technology.

Let's start OAuth Integration with Twitter in step by step process.

Configuration Used

  1. Visual studio 2015
  2. SQL Server 2008 R2

Database part

We are going to create Database with Name "MVC5DEMODB" in SQL Server 2008 R2

Create New Asp.Net MVC Application

From Visual studio 2015 IDE Start page click on "New Project" link.

After clicking on "New Project" link a new dialog will pop up.

In that we are going to select web templates from left pane after selecting web template, we find only one project template in it "ASP.NET Web Application" just select that.

After selecting this project template next we are going to name the project as "MVC5DEMO3" and clicking on the OK button a new dialog will pop up with Name "New ASP.NET Project" for selecting project Templates.

In this dialog, we are going to choose MVC project template and then we are going to choose Authentication type for doing that just click on Change Authentication button, a new dialog will pop up with name "Change Authentication" here we are going to choose Individual User Accounts .

Note: - Individual User Accounts

If you choose this option for Authentication of application then your application will be configured to use ASP.NET identity [ASP.NET Membership] where User register in the application and then sign in using credentials and also User sign in via social accounts such as Facebook, Twitter, Google, Microsoft and other providers. All user data will be stored in SQL server database.

After selecting Authentication type as Individual User Accounts click on OK Button.

It will show a progress bar while it is creating a project.

After creating a project it will show Readme HTML page with useful links on that page.

And in right part, you will see newly created project structure.

As we have chosen Individual User Accounts Authentication type we got ready made Membership Model added in Models folder as shown below.

Project structure

Complete Project structure after creating new project.

Models Folder View

After creating project successfully now let's add connection string to project

Adding Connection String in Web.config file

<connectionStrings>
    <add name="DefaultConnection"
       connectionString="Data Source=sai-pc;Database=MVC5DEMODB;UID=sa;Password=Pass$123"
      providerName="System.Data.SqlClient" />
  </connectionStrings>

After adding Connection string next step just save current project and RUN.

Homepage View in browser after running application

After homepage appears just click on Register link, then Register page will appear.

After Register page appear enter details required for registration.

After filling data just click on Register button meanwhile Microsoft.AspNet.Identity will generate tables in the database as shown below.

Database View after registering User

Along with this, it will also save data in these tables.

Just have a look on below snapshot it is data which we have filled while we have registered in the application.

If you look out properly you will as see other tables in the database which stored data related to Role and Role.

Tables and its Details

AspNetRoles : - which stored data related to Role.

AspNetUserRoles: - which stored data related to Role assigns to User.

AspNetUsers: - which stored data related to User.

AspNetUserLogins: - which stored data related to Login Provider [Google, Facebook, Twitter] [ProviderKey, UserId].

After Completing with Database part let's move back to Application part.

Now you are logged into application if you want you can log out and retry to log in.

It is the traditional way to doing it.

Now let move toward Implementing External Authentication provider like Twitter.

Implementing External Authentication provider Twitter

In this part of implementation, we do not require to do any coding part it's all about configuration.

All configuration starts with Startup.Auth.cs

Startup.Auth file in Asp.Net MVC

This Class (Startup.Auth.cs) file is created by default when we create application and it is located inside App_Start as shown below

Now let's take a view on Startup.Auth.cs file and see what it contains.

The Startup.Auth.cs file contains all OAuth Clients comment by default. We are going to implement an example of OAuth with Twitter for that we need to uncomment Twitter client first.

Register Application with Twitter

In this part we are going to register our application with Twitter but for doing this process we need to have account on Twitter if it is not there then we need to create account for this demo, if you already have Twitter than that good you are ready to take ride just login into your Twitter account past given URL: - https://apps.twitter.com/ , below view, must appear after pasting URL.

After logged into https://apps.twitter.com/ next step is to click on "Create New App" button as shown in above snapshot. After clicking on Create New App button it will redirect to create an Application page.

In this page, we are going fill information regarding our App.

Steps to create application

First thing we are going to fill Name. This name will be your App name and it must be Unique I am entering it as MVCTwitterDemo.

Second thing we are going to fill Description - MVC 5 Demo OAuth with Twitter

Third thing we are going to fill Website URL this URL might be company site URL or your personal site URL if you don't have website then you can add any name in future can change here we are entering it as "http://MVCTwitterDemo.com"

Last thing we also need to Provide Callback URL which is Not Mandatory.

To see URI just right click on the MVC5DEMO3 project then select properties from the list which is at the bottom.

In that we are next going to choose Web tab in web tab you can see project URI: - http://localhost:2700/ just copy this URL and paste it in Callback URL Textbox.

After setting Callback URL next step is to agree Twitter Development Agreement and final click on "Create your Twitter application" button.

After clicking on "Create your Twitter application" button it will take you to app view where it will show app Details.

[Details, Setting, key and Access Tokens, Permission] as shown below snapshot.

In next part just click on key and Access Tokens tab it will show you Consumer Key (API Key) and Consumer Secret (API Secret) which is need as shown in below snapshot.

Just copy and paste Consumer Key and Consumer Secret to Startup.Auth.cs class as shown in below snapshot.

Then Save your application and run.

After running the application it will take you to the login page as shown below.

You must see twitter button on Login view, now just click on twitter button to log in it shows error as shown in below snapshot

Displaying Error after Clicking on Twitter button

"The remote certificate is invalid according to the validation procedure."

Recently some certificates must have changed and now the thumbprints no longer match.

Note: - Please add a new thumbprint for the "VeriSign Class 3 Public Primary Certification Authority - G5" Certificate to your Twitter Auth Options in your Startup.Auth.cs.

Comment this below code

Comment is code in Startup.Auth.cs

After commenting above code at that place we are going to use below code snippet with VeriSign certificates for twitter OAuth.

Replacing piece of code

Code snippet

app.UseTwitterAuthentication(new TwitterAuthenticationOptions
            {
                ConsumerKey = "XXXXXXXXXXXXXXXXXXXXXX",
                ConsumerSecret = " XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX ",
                BackchannelCertificateValidator = new Microsoft.Owin.Security.CertificateSubjectKeyIdentifierValidator(new[]
                {

                  "A5EF0B11CEC04103A34A659048B21CE0572D7D47", // VeriSign Class 3 Secure Server CA - G2
                  "0D445C165344C1827E1D20AB25F40163D8BE79A5", // VeriSign Class 3 Secure Server CA - G3
                  "7FD365A7C2DDECBBF03009F34339FA02AF333133", // VeriSign Class 3 Public Primary CA - G5
                  "39A55D933676616E73A761DFA16A7E59CDE66FAD", // Symantec Class 3 Secure Server CA - G4
                  "‎add53f6680fe66e383cbac3e60922e3b4c412bed", // Symantec Class 3 EV SSL CA - G3
                  "4eb6d578499b1ccf5f581ead56be3d9b6744a5e5", // VeriSign Class 3 Primary CA - G5
                  "5168FF90AF0207753CCCD9656462A212B859723B", // DigiCert SHA2 High Assurance Server C‎A 
                  "B13EC36903F8BF4701D498261A0802EF63642BC3"  // DigiCert High Assurance EV Root CA
                })
            });

Just copy this code snippet and past in Startup.Auth.cs class and replace your own Consumer Key and Consumer Secret.

Then Save your application and run again

Back to Login view.

Now on Login page you can see twitter button again on Login view, now just click on twitter button to log in it will take you to the login page of Twitter as show below.

Just enter your Twitter credentials and click on Sign in button.

After Clicking on login button it will authenticate your request as shown below.

After authentication, it will redirect to ExternalLoginCallback view and on that view you will see Email textbox which will tell you to enter Email ID (saihacksoft@gmail.com).

After entering Email ID in textbox now just click on Register button and you are login into application.

Following is the snapshot which shows you are logged in your application.

Now let's check out where this data is been added in (MVC5DEMODB) database tables.

First, we will look on AspNetUserLogins table.

AspNetUserLogins table

This table store data related to LoginProvider.

As you can see it is storing data of Twitter login.

AspNetUsers table

This table store data related to all Users from Oauth login as well as from Traditional.

If it contains PasswordHash then it is registered by Traditional Login and if it is PasswordHash is empty then it is done by OAuth login.

Finally, we completed understanding what OAuth is and how to use with asp.net MVC 5 applications and also had an example of OAuth integration with Twitter.

+91-22-66752917
+91 9967590707
questpond@questpond.com / questpond@yahoo.com