oAuth Login with Twitter in Asp.Net MVC Website with Example

Here we will learn how to implement the OAuth service that is provided by Twitter in ASP.NET MVC. Generally, ASP.NET MVC4 has inbuilt features of Oauth.

 

Twitter sign in option in asp.net mvc web application

 

Now let’s explorer Oauth step by step, starting from creating Application in asp.net mvc. 

Create New Asp.Net MVC Application

Let's start with creating a new asp.net mvc 4 application for that Open visual studio à Go to File à Select New à Select Project.

 

create new asp.net mvc project from visual studio 2012

 

After that, you will see a new dialog for selecting your Template and Project type. From Templates, select Visual C# à inside that select Web and then project type select ASP.NET MVC 4 Web Application, and here we are giving the name as “Tutorial13” finally click on OK button.

 

create asp.net mvc web application in twitter login

 

After naming and click on the OK button, a new dialog will pop up for selecting a template in that Select Internet Application template and set view engine as Razor. We are not going to create Unit testing for this project hence do not check this option and finally click OK like as shown below.

 

select internet application template for asp.net mvc twitter sign in project

 

After selecting all options as told above, click on the OK button, your Project will be created like as shown below.

 

asp.net mvc application structure for twitter sign in option

After successfully created applications, let’s move towards creating Database.

Create New Database

Create a database in SQL Server with any name, but we are naming it “AuthDB”.

 

create new database in sql server for asp.net mvc authentication example

 

After creating a database that will be as shown below.

 

New database structure in asp.net mvc application

 

After creating a Database with the name “AuthDB”, let's add a connection string to the project.

 

<connectionStrings>

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

</connectionStrings>

After adding the connection string now let's add Membership tables to the AuthDB database. Before that let’s have look at model (AccountModels) and it's located in Models Folder which is created Default if you are choosing Internet Application Template that will be like as shown below.

 

Account models code structure in asp.net mvc oauth login

 

AccountModels file will contain code like as shown below.

 

Account models code structure in asp.net mvc oauth login

InitializeDatabaseConnection in Global.asax for Creating Membership tables

Here we are going to use the Code First Approach of Entity Framework. For adding Membership tables to the database, we need to add a single line of the following code in Global.asax.

 

WebSecurity.InitializeDatabaseConnection("DefaultConnection""UserProfile""Id""UserName", autoCreateTables: true);

The above line will create all Membership tables. For this method, we need to provide parameters like as shown above. Following is a brief description of the InitializeDatabaseConnection method.

 

InitializeDatabaseConnection Method Metadata

 

public static void InitializeDatabaseConnection (string connectionStringName, string userTableName, string userIdColumn, string userNameColumn, bool autoCreateTables);

Parameters

 

The following are the parameters we used the intializedatabaseconneciton method.

 

  • connectionStringName: The name of the connection string for the database that contains user information. If you are using SQL Server Compact, this can be the name of the database file (.sdf file) without the .sdf file name extension.        
  • userTableName: The name of the database table that contains the user profile information.        
  • userIdColumn: The name of the database column that contains user IDs. This column must be typed as an integer (int).        
  • userNameColumn: The name of the database column that contains user names. This column is used to match user profile data to membership account data.        
  • autoCreateTables: True to indicate that user profile and membership tables should be created if they do not exist; false to indicate that tables should not be created automatically. Although the membership tables can be created automatically, the database itself must already exist.

 

Once we add our database connection in our Global.asax file, that will be shown below.

 

Global.asax file in asp.net mvc applicaiton with database conneciton

 

After completion of all the configurations, let’s run the application and check. After running the application, you will find the Default home page on that page at the right corner you will find the register link click on it and wait for some time a Register page will popup like as shown below.

 

Initial user registration page in asp.net mvc with example

 

If you are getting error in creating membership tables, remove the [InitializeSimpleMembership] attribute from AccountController.

 

[Authorize]

[InitializeSimpleMembership]

public class AccountController : Controller

{

 

}

After opening the Register page, open the database that we created, “AuthDB” expand it. Inside the tables section, we can see all Membership Tables created like as shown below.

 

Database with asp.net mvc membership tables in oauth login

 Now we completed the database part. Let's make modifications in the AuthConfig file to enable Oauth Twitter login.

AuthConfig file in Asp.Net MVC

Oauth( AuthConfig.cs) file is created by default when we create an application, and it is located inside the App_Start folder with Name AuthConfig.cs like as shown below.

 

AuthConfig file in app_start folder in asp.net mvc project

 

Now let’s take a view of the AuthConfig.cs file and see what it contains.

 

Authconfig file with all oauth client details default in commenting

 

The AuthConfig.cs file contains all OAuth Clients comments by default. We will implement an example of OAuth with Twitter for that we need to uncomment the Twitter clients first.

 

Uncomment twitter oauth client in asp.net mvc application

 

Now you can run the application, but it will throw an error because we have not provided ( consumerKey: "", consumerSecret: "" ) for this first, we need to Register Application with Twitter.

Register Application with Twitter

Before proceeding with the next step, you must have a Twitter account to register your application on Twitter. If you have the account already, login into the account, else create a new account, then login. After logging into your own account, just past this Url in browser: "https://apps.twitter.com/" to create your own app on Twitter.

 

Open twitter website to create new app in asp.net mvc

After logged into https://apps.twitter.com/ next step, click on the “Create New App” button as shown in the above snapshot. After clicking on the Create New App button, it will redirect to the Create an Application page. In this page, we are going to fill information regarding our App.

 

  1. The 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 OauthTwitterdemotest
  2. The second thing we are going to fill Description - My OauthTwitterdemo
  3. The third thing we are going to fill in the Website URL. This URL might be a company site URL or your personal site URL. If you don’t have a website, you can add any name in the future, and you can change it to "http://localhosttest.com".
  4. Last thing, we also need to Provide a Callback URL that is Not Mandatory.

 

Fill all details to create new twitter application

 

After filling details, we need to agree on the Developer Agreement to Create App. Just check the Yes, I agree option and click on the Create your Twitter application button.

accept terms and conditions to create new app in twitter

After clicking on the Create your Twitter application button, your application will create. The following are the complete Details of App which we have created.

 

After creating new app in twitter

Now click on Keys and Access Tokens Menu to get your [ consumerKey: "" , consumerSecret: "" ]

 

Getting consumer API Keys and consumer API Secret in twitter

 

After that, copy consumerKey and consumerSecret key values and add it to AuthConfig.cs file like as shown below.

 

Adding consumer key and consumersecret key in twitter asp.net mvc application

 

After adding, save your application and Run. We will see a login page with Twitter login option like as shown below.

 

Twitter login option in asp.net mvc application

 

After running the application, you will see the Twitter button on the right part of the login page. Now click on the Twitter button, then it will take you to the Twitter login page here you just entire Twitter credentials and login in to Twitter while redirecting might there is a chance to get error like as shown below

 

Get error while redirecting to twitter login page in asp.net mvc application

 

To resolve this error you need to enter Callback URL which we had not entered will Creating Application on twitter just login to twitter account and enter Callback URL for OauthTwitterdemotest App this will resolve Error.

 

Enter call back url in twitter application

 

After entering Callback URL click on Update Setting button to update details. Now refresh your application and again try to click on Twitter button. After clicking on Twitter button now it will take you to https://api.twitter.com/ to sign in as shown below.

 

Twitter login to get access permission for new application

 

Here need to enter Twitter credentials to login in to Twitter. After login it will redirect to ExternalLoginCallback view and on that view you will see Username textbox which contains Username (saihacksoft) which we have got from Twitter Oauth service. We have not written any code for it till now we have just configured it.

 

Redirect to asp.net mvc application with registered twitter username

 

After getting on ExternalLoginCallback view and Username filled in textbox, click on the Register button and log in to the application. Following is the snapshot which shows you are logged in your application.

 

After login into asp.net mvc application with twitter account

 

Now let’s checkout where this data is been added in (AuthDB) database tables. First we will look on UserProfile table. 

 

User Profile table with twitter login details in asp.net mvc

 

Second table which we are going to look upon is webpages_OAuthMembership table. 

 

oauth membership table which contains twitter login userdetails

 

In this table the data of Oauth provider is stored and it is saved successfully. Finally we completed understanding what Oauth and how to use with asp.net mvc application and had an example of Oauth integration with Twitter.