Here we will learn what is Oauth, and with this, we will see an example of how to implement the OAuth service provided by Facebook in ASP.NET MVC. Most of the web applications nowadays are providing Oauth login to access to there Application. Generally, Oauth is an open standard for authentication and authorization.
Nowadays, many e-commerce sites to buy one product with a low price to register and remember Email ID and the Password of all those sites will be headaches because there is a solution known as Oauth.
If we check any e-commerce portals, they have Google, Facebook, and Twitter buttons on the login page. If we click on the Facebook button, it will take us to the Facebook portal to login with our Facebook credentials. It will ask for access to 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 the okay button automatically, we will register, and we are logged inside the Ecommerce application.
In the above example, the 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.
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.
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 “Tutorial12” then finally click on OK button.
After naming and click on the OK button, now new dialog will pop up for selecting a template in that Select Internet Application template and set view engine as Razor. We will not create Unit testing for this project; hence, do not check this option and finally click OK like as shown below.
After click on the OK button, wait for some time to configure the solution for you. After creating the project, our project will be ready, and it contains a lot of MVC folder structure and other script and .css style like as shown below.
After successfully creating applications, now let’s move towards creating Database.
Create a New Database
Now, create a SQL Server database with any name, but we are naming it “AuthDB”.
After creating a database that will be as shown below.
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$123" providerName="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.
AccountModels file will contain code like as shown below.
InitializeDatabaseConnection in Global.asax for Creating Membership tables
Here we are going to Use the Code First Approach of Entity Framework. To add 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, and 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.
After completion of all configurations, let’s run the application and check. After running the application, you will find the Default homepage on that page at the right corner. You will find the register link, click on it, and wait for a Register page to pop up as shown below.
If you are getting error in creating membership tables, remove the [InitializeSimpleMembership] attribute from AccountController.
public class AccountController : Controller
{
}
After opening the Register page, verify the database we created “AuthDB” expand the database. Inside the tables section, we can see all Membership Tables that created like as shown below.
Now we completed the database part. Let's make modifications in the AuthConfig file to enable the Oauth Facebook 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.
Let’s take a view of the AuthConfig.cs file and see what it contains.
The AuthConfig.cs files contain all OAuth Clients comments by default. We will implement an example of OAuth with Facebook for that, we need to uncomment the Facebook client first.
Now you can run the application, but it will throw an error because we have not provided ( appId: "", appSecret: "" ). For this, we first need to Register an Application with Facebook.
Register Application with Facebook
Before proceeding with the next step, you must have a Facebook account to register your application on Facebook. If you have, login into it; else create a new account then login. After logging into your own account, past this Url in browser: "http://developers.facebook.com/" to register your own site. After opening developer site next step is to select “My Apps” as shown in the below snapshot.
After clicking on the “My Apps” menu Apps page will open with the “Create a New App” button like as shown below
Create a New App ID on Facebook
After clicking on the “My Apps”, you will see a new page with a button “Create a New App” click on that button. After that, a popup will open with the Name “Create a New App ID”. In that, fill all options, the Display Name will be your App Name here we are entering OauthDemo and 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 the “Create App ID” button, we will have a security check like as shown below.
After passing the security check, your app is created, and you will be redirected to the dashboard page. On the dashboard page, you will get your ( appId: "", appSecret: "" ) details to use for the Facebook Oauth service. The following snapshot shows where you will see ( appId: "", appSecret: "" ) on the dashboard page.
After that, we need to set our App Domains. For setting this first, we need to click on setting just below the Dashboard. We will see the +Add Platform button click on it. A new dialog will open to select Platform inside that we are going to select the Website.
After selecting the add platform, a small panel will popup asking for the Site URL. Here, you will be adding your project URL like "http://localhost:2222/". To see where the project URL is, right-click on Project, select Properties like as shown below.
After selecting Properties, a new window will open inside that select Web Menu just below Build at the bottom of the page. You will see Project URL, which we highlighted in yellow here project URL like "http://localhost:2222/". Just copy that URL.
After copying, paste that URL inside Site URL (http://localhost:2222/) and then click on the save changes button.
After that, copy App ID and App Secret and add in AuthConfig.cs files.
After adding, save your application, Run the application. Following is our login page after adding oAuth Facebook login in asp.net mvc application.
After running the application, you will see the Facebook button on the login page's right part. Now click on the Facebook button. It will take you to the Facebook login page here. You enter Facebook credentials and login to Facebook.
After login into Facebook, a 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 click on the Okay button to proceed further.
After clicking on the okay button, it will redirect to the ExternalLoginCallback view. You will see Username textbox, which contains Username (Saineshwar Bageri) that we have got from the Facebook Oauth service. We didn't write any code, just configured it using oAuth service in asp.net mvc.
After getting on ExternalLoginCallback view and Username filled in the textbox, click on the Register button and log in to the application. Following is the snapshot that shows you are logged in to your application.
Now let's check out where this data is added in (AuthDB) database tables.
The user name is successfully saved in the UserProfile table, and the second table, which we will look upon, is the webpages_OAuthMembership table.
In this table, the data of the 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 it with asp.net mvc application and had an example of Oauth integration with Facebook.