Here we will learn what is Oauth and with this we are going to see example of how to implement Oauth service which is provided by Facebook in ASP.NET MVC. Most of web application now days are providing Oauth login to access to there Application. Generally Oauth is open standard for authentication and authorization.
Now a days lot of e-commerce sites to buy one product with low price to register and remember Email ID and Password of all those sites will be head ache for that there is solution for it known as Oauth.
If we check any of e-commerce portals they have Google, Facebook and twitter button on login page. If we click on Facebook button then it will take us to Facebook portal for login with our Facebook credentials and then it will ask access for public profile and EmailID information (Your public profile includes name, profile picture, age range, gender, language, country and other public info) when we click on okay button then automatically we will register and we are logged inside Ecommerce application.
In above example client application will be (flipkart, snapdeal, Amazon, Jabong) and Oauth providers will be (Google, Facebook, Twitter, LinkedIn, Microsoft and Yahoo). In asp.net mvc 4 have inbuilt features of Oauth. Now let's explorer Oauth step by step starting from creating Application in asp.net mvc.
Let's start with creating new asp.net mvc 4 application for that Open visual studio studio à Go to File à Select New à Select Project
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 “Tutorial12” then finally click on OK button
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
After click OK button wait for some time it requires some seconds for configuring solution for you. After creating project our project will be ready and it contains whole lot MVC folder structure and other script and .css style like as shown below
After successfully creating application now let’s move towards creating Database.
Now create database in SQL Server with any name but we are naming it “AuthDB”
After creating database that will be like as shown below
After creating Database with name “AuthDB” now let's add connection string to project
<add name="DefaultConnection" connectionString="Data Source=sai-pc;Database=AuthDB;UID=sa;Password=Pass$123" providerName="System.Data.SqlClient" />
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
AccountModels file will contain code like as shown below.
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);
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.
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
If you are getting error in creating membership tables then remove [InitializeSimpleMembership] attribute from AccountController
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
Now we completed database part. Let's make modification in AuthConfig file to enable Oauth facebook login.
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
Now let’s take view on AuthConfig.cs file and see what it contains.
The AuthConfig.cs files contains all OAuth Clients comment by default. We are going to implement example of OAuth with Facebook for that we need to uncomment Facebook client first.
Now you can run application but it will throw error because we have not provided ( appId: "", appSecret: "" ) for this we first need to Register Application with Facebook.
Before proceed with next step you must have Facebook account to register your application on Facebook 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: "http://developers.facebook.com/" to register your own site. After opening developer site next step is select “My Apps” as shown in below snapshot.
After clicking on “My Apps” menu Apps page will open with “Create a New App” button like as shown below
After clicking on “My Apps” you will see new page with button “Create a New App” just click on that button after that a popup will open with Name “Create a New App ID”. In that fill options Display name will be your App Name here we are entering OauthDemo. Namespace is not mandatory we are leaving that option empty in category I am going to select Education and then finally click on “Create App ID” button.
After clicking on “Create App ID” button we will have security check like as shown below.
After passing Security check your app is created and you will be redirected to dashboard page and on dashboard page you will get your ( appId: "", appSecret: "" ) which we need to Used Facebook Oauth service. The following snapshot shows where you will see ( appId: "", appSecret: "" ) on dashboard page.
After that we need to set our App Domains. For setting this first we need to click on setting just below Dashboard then we will see +Add Platform button just click on it. A new dialog will open to select Platform inside that we are going to select Website.
After selecting add platform a small panel will popup asking Site URL here you will be adding your project URL like "http://localhost:2222/". To see where project URL is just right click on Project then select Properties like as shown below.
After selecting Properties a new window will open inside that select Web Menu just below Build at bottom of page you will see Project URL which we highlighted in yellow here project URL like "http://localhost:2222/". Just copy that URL.
After copying just paste that URL inside Site URL (http://localhost:2222/) and then click on save changes button.
After that just copy App ID and App Secret and just add in AuthConfig.cs files.
After adding just save your application then Run application. Following is our login page after adding oAuth facebook login in asp.net mvc applicaition.
After running application you will see Facebook button on right part of login page. Now just click on Facebook button then it will take you to Facebook login page here you just enter Facebook credentials and login in to Facebook.
After login in to Facebook site now new dialog will pop up for allowing App to access your profile information (Your public profile includes name, profile picture, age range, gender, language, country and other public info). Now just click on Okay button to proceed further.
After clicking on okay button it will redirect to ExternalLoginCallback view and on that view you will see Username textbox which contains Username (Saineshwar Bageri) which we have got from Facebook Oauth service. Till now we didn't written code just configured it using oAuth service in asp.net mvc.
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 that shows you are logged in your application.
Now let's checkout where this data is been added in (AuthDB) database tables.
The user name is successfully saved in UserProfile table and second table which we are going to look upon is webpages_OAuthMembership table.
In this table the data of Oauth provider is stored and it is saved successfully. If you want more information from Facebook related to User then you need to install API from Nuggets package solution like as shown below.
Finally we completed understanding what Oauth is and how to use with asp.net mvc application and also had an example of Oauth integration with Facebook.