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

  Total Views : 1607
  Comments : 0
 
  Keywords : How to configure twitter sign-in option in asp.net mvc using oauth, How to add twitter login authentication to webiste in asp.net mvc, Login with twitter account in asp.net mvc website

Here we will learn how to implement Oauth service which is provided by Twitter in ASP.NET MVC. Generally ASP.NET MVC4 have 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 new asp.net mvc 4 application for that Open visual studio studio à Go to File à Select New à Select Project

 

create new asp.net mvc project from visual studio 2012

 

After that you will see new dialog will pop up 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 name as “Tutorial13” then finally click on OK button

 

create asp.net mvc web application in twitter login

 

After naming and click on OK button now new dialog will pop up for selecting template in that Select Internet Application template and set view engine as Razor and 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 option as told above now click OK button your Project will be created like as shown below

 

asp.net mvc application structure for twitter sign in option

After successfully created application now let’s move towards creating Database.

Create New Database

Now create 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 database that will be like as shown below

 

New database structure in asp.net mvc application

 

After creating Database with name “AuthDB” now let's add connection string to 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 Code First Approach of Entity Framework. Now for adding Membership tables to database we need to add a single line of 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 the brief descript about InitializeDatabaseConnection method

 

InitializeDatabaseConnection Method Metadata

 

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

Parameters

 

Following are the parameters we used 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 conneciton in our Global.asax file that will be like as shown below

 

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

 

Finally after all configuration now let’s run application and check. After running application you will find Default homepage on that page at right corner you will find register link just 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 then remove [InitializeSimpleMembership] attribute from AccountController

 

[Authorize]

[InitializeSimpleMembership]

public class AccountController : Controller

{

 

}

Now after popping up of Register page have look on database which we created “AuthDB” just expand database and inside tables section we can see all Membership Tables which created like as shown below

 

Database with asp.net mvc membership tables in oauth login

 Now we completed database part. Let's make modification in AuthConfig file to enable Oauth twitter login

AuthConfig file in Asp.Net MVC

Oauth( AuthConfig.cs) file is created by default when we create application and it is located inside 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 view on 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 comment by default. We are going to implement example of OAuth with Twitter for that we need to uncomment Twitter client first.

 

Uncomment twitter oauth client in asp.net mvc application

 

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

Register Application with Twitter

Before proceed with next step you must have Twitter account to register your application on Twitter if you have then login in to it else create a new account then login. After logged in to 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 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.

 

  1. 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. Second thing we are going to fill Description - My OauthTwitterdemo
  3. 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://localhosttest.com"
  4. Last thing we also need to Provide Callback URL which is Not Mandatory.

 

Fill all details to create new twitter application

 

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

accept terms and conditions to create new app in twitter

After clicking on Create your Twitter application button your application will creat. Below is 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 just copy consumerKey and consumerSecret key values and add it in AuthConfig.cs file like as shown below

 

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

 

After adding just save your application and Run. We will see login page with twitter login option like as shown below

 

Twitter login option in asp.net mvc application

 

After running application you will see Twitter button on right part of login page. Now just click on Twitter button then it will take you to 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 just 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 now just click on Register button and you are login in to 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 is Oauth and how to use with asp.net mvc application and also had an example of Oauth integration with Twitter. 

 Comments (0)

Be the first to give your valuable feedback

Leave a comment

  • Default Tutlane User