How to Login with Facebook in ASP.NET MVC

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 mvc 4 have inbuilt features of Oauth. Now let's explorer Oauth step by step, starting from creating Application in mvc.

Create New Asp.Net MVC Application

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

create new 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 “Tutorial12” then finally click on OK button.

select mvc 4 web application and click ok to create new mvc application

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.

select internet application template for mvc oauth social login project

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.

Facebook login authentication in mvc application

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”.

create new database in sql server for mvc authentication example

After creating a database that will be as shown below.

New database structure in mvc application

After creating a Database with the name “AuthDB”, let's add a connection string to the 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.

After adding accountmodels file in mvc application

AccountModels file will contain code like as shown below.

Account models code structure in mvc oauth login

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);


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 mvc applicaiton with database conneciton

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.

Initial user registration page in 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, 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.

Database with mvc membership tables in oauth login

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.

AuthConfig file in app_start folder in mvc project

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 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.

Uncomment facebook oauth client in mvc application

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: "" to register your own site. After opening developer site next step is to select “My Apps” as shown in the below snapshot.

create new app from facebook developer website in mvc oauth facebook login

After clicking on the “My Apps” menu Apps page will open with the “Create a New App” button like as shown below

create new app in facebook in mvc oauth social login

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.

Give details required to create new app in facebook

After clicking on the “Create App ID” button, we will have a security check like as shown below.

select security image to create new app in facebook

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.

Newly created app details in mvc application

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.

add website domain to app in facebook

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.

change properties of mvc website

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.

get project url from project build in mvc oauth application

After copying, paste that URL inside Site URL (http://localhost:2222/) and then click on the save changes button.

Enter website url to create new app in facebook

After that, copy App ID and App Secret and add in AuthConfig.cs files.

Add facebook appid details in mvc oauth application

After adding, save your application, Run the application. Following is our login page after adding oAuth Facebook login in mvc application.

login page with oauth facebook login option in mvc social login

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.

enter facebook credentials to login facebook app in mvc application

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.

Allow access permission to app to login with facebook in mvc

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 mvc.

register new user with facebook details in mvc application

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. mvc application after login with facebook using oAuth social plugins

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

userprofile table with facebook register user details

The user name is successfully saved in the UserProfile table, and the second table, which we will look upon, is the webpages_OAuthMembership table.

oauth membership table which contains facebook login userdetails

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.

install facebook api in mvc application to get more details

Finally, we completed understanding what Oauth is and how to use it with mvc application and had an example of Oauth integration with Facebook.

Rate this post
error: Content is protected !!