Working With Facebook and Google OAuth2 and OpenID in Visual Studio 2013

Introduction

Today we'll learn how to authenticate an ASP.NET MVC Web Application using OAuth 2.0 like Facebook and Google. There are various types of external authentication providers available for authenticating applications like Facebook, Google, Twitter and Microsoft and here we'll use to authenticate the app by Facebook and Google.

In that context, I am using the Visual Studio 2013 RTM and in it the MVC 5 Project Template is used to create the ASP.NET application. You can get the rich advantage in the website by enabling external providers because billions of users already have accounts with these. They can sign up with these providers instead of registering a new set of credentials.

You'll learn also to add more profile data while associating the external provider with the MVC application. So, let's get started with the following sections:

  • MVC Web application
  • Working with Google OpenID
  • Enable SSL in Project
  • Creating and Working with Facebook App
  • Membership Information in MVC App
  • Add More Profile Data

MVC Web Application

As I mentioned above here I am using Visual Studio 2013 to create the web application. Use the following procedure.

Step 1: Open Visual Studio 2013 and click on "New Project".

Visual Studio 2013 Start Page

Step 2: Select the ASP.NET Web application and provide a name.

Create ASP.NET Web App

Step 3: In the next wizard select the MVC Project Template to create the application.

Mvc Project Template in VS 2013

Note: Please ensure that "Individual User Accounts" is selected in the Change Authentication.

Step 4: Click on "OK" and the MVC application is created automatically. Now open the layout file.

Shared Layout FIle in Mvc App

Step 5: Now modify the application name and title as shown below:

Layout File in Mvc App

Step 6: Press Ctrl+F5 or F5 to run the application.

Home Page of Mvc App

Working with Google OpenID

In this section we'll enable the Google authentication for the application using the following procedure.

Step 1: Open the Startup_Auth.cs file

Startup File in Mvc App

Step 2: Uncomment the code to enable Google Authentication as shown in the code below:

            //app.UseFacebookAuthentication(

            //   appId: "",

            //   appSecret: "");

 

            app.UseGoogleAuthentication();

        }

    }

}

Step 3: Now run the application and click on "LogIn".

LogIn in Mvc App

Step 4: In the Login page click on "Google".

Google Login Auth Service in Mvc

Step 5: Enter the credentials for Google Account and you'll be prompted to authenticate the Localhost.

Localhost Authentication in Google

Note: You can check that the URL contains the "openid2" because these providers don't require you to create an app with the authentication provider.

Step 6: Now you will be redirected back to the Register page and enter the user name to register.

Register Google Auth in MVC

Step 7: Now you will be logged in with Google. Check it out

Registered with Google Auth in MVC

Enable SSL in Project

We need to set up IIS Express to use the Secured Socket Layer (SSL) to connect with Facebook by enabling the SSL. It's important to keep using the SSL after login and not drop back to HTTP, you rlogin cookie is just as secret as your username and password and without SSL you're sending it in clear text across the wire. So, let's proceed with the following procedure.

Step 1: Select the project in the Solution Explorer and press F4 to open the properties.

Step 2: Enable SSL to true and copy the SSL URL.

Enable SSL in Mvc App

Step 3: Now right-click on the project to open the properties of your project.

Step 4: Select the web tab and in the Project URL, paste the SSL URL as shown below:

Setting Up Project URL in MVC App

Step 5: Save the application. We'll need this URL later to configure the Facebook App.

Creating and Working with Facebook App

In this section we'll create an app on Facebook to connect with the application. Use the following procedure.

Step 1: Navigate to https://developers.facebook.com  and log into Facebook.

Step 2: Now in the Apps, click on "Create a New App".

Creating App on Facebook

Step 3: Enter the App name and namespace and choose "Category".

Create New App on Facebook

Step 4: Now click on "Add Platform".

Add Platform for Facebook App

Step 5: Select the Website platform.

Selecting Website Platform in Fb App

Step 6: Click on "Settings" on the left pane and paste the SSL URL in the Site URL. Copy the App ID and App Secret (used later) and click on "Save Changes".

Facebook App Settings for Mvc App

Step 7: Now again open the Startup_Auth.cs file and paste in the App ID and App Secret value as shown below:

Facebook App Setup in Mvc App

Step 8: Save the application and run the application. You'll get the security certificate warning in IE, Firefox and Chrome or Page Inspector. This happens because IIS Express used a certificate not trusted by the browsers. You can ignore the warning and proceed to the website.

Security Certificate Warning

Step 9: Click on "Login" and use the Facebook service to login.

Facebook Login Auth Service in Mvc

Step 10: Now enter the Facebook credentials to log in with Facebook.

Facebook Login

Now you will be prompted to grant the permission for the app to access the profile and friends list.

Authenticating Fb App

Step 11: Now register and associate the Facebook account.

Register Facebook Auth in MVC

Step 12: Now you will be logged in with Facebook. Check it out.

Registered with Facebook Auth in MVC

Membership Information in MVC App

In this section, we'll check out the users that are logged in with their accounts using the following procedure.

Step 1: Open Server Explorer and expand the DefaultConnection to open the tables.

Step 2: Right-click on AspNetUsers to open the table data.

Users Table Data in Server Explorer

All users are shown in the table as shown below:

Users Table

Add More Profile Data

In this section, we'll add some more profile related data to be associated with the external providers using the following procedure.

Step 1: Open the Models\IdentityModels.cs file and modify the code with the highlighted code below:

using System;

 

namespace MvcSocialAuthentication.Models

{

    public class ApplicationUser : IdentityUser

    {

        public string City { get; set; }

        public DateTime? DateofBirth { get; set; }

    }

 

    public class ApplicationDbContext : IdentityDbContext<ApplicationUser>

    {

        public ApplicationDbContext()

            : base("DefaultConnection")

        {

        }

    }

}

Step 2: Open the Models\AccountViewModels.cs file and modify the code with the highlighted code below:

using System;

using System.ComponentModel.DataAnnotations;

 

namespace MvcSocialAuthentication.Models

{

    public class ExternalLoginConfirmationViewModel

    {

        [Required]

        [Display(Name = "User name")]

        public string UserName { get; set; }

        public string City { get; set; }

        [Display(Name= "Birth Date")]

        public DateTime? DateofBirth { get; set; }

    }

Step 3: Open the Controllers\AcountController.cs file and modify the code with the highlighted code below:

public async Task<ActionResult> ExternalLoginConfirmation(ExternalLoginConfirmationViewModel model, string returnUrl)

{

    if (User.Identity.IsAuthenticated)

    {

        return RedirectToAction("Manage");

    }

 

    if (ModelState.IsValid)

    {

        // Get the information about the user from the external login provider

        var info = await AuthenticationManager.GetExternalLoginInfoAsync();

        if (info == null)

        {

            return View("ExternalLoginFailure");

        }

        var user = new ApplicationUser() {

            UserName = model.UserName,

            City=model.City,

            DateofBirth=model.DateofBirth

        };

Step 4: Open the Views\Account\ExternalLoginConfirmation.cshtml file and modify the code with the highlighted code below:

<div class="form-group">

    @Html.LabelFor(m => m.UserName, new { @class = "col-md-2 control-label" })

    <div class="col-md-10">

        @Html.TextBoxFor(m => m.UserName, new { @class = "form-control" })

        @Html.ValidationMessageFor(m => m.UserName)

    </div>

</div>

<div class="form-group">

    @Html.LabelFor(m => m.City, new { @class = "col-md-2 control-label" })

    <div class="col-md-10">

        @Html.TextBoxFor(m => m.City, new { @class = "form-control" })

        @Html.ValidationMessageFor(m => m.City)

    </div>

</div>

<div class="form-group">

    @Html.LabelFor(m => m.DateofBirth, new { @class = "col-md-2 control-label" })

    <div class="col-md-10">

        @Html.TextBoxFor(m => m.DateofBirth, new { @class = "form-control" })

        @Html.ValidationMessageFor(m => m.DateofBirth)

    </div>

</div>

<div class="form-group">

Step 5: Now to delete the existing database file, in Solution Explorer, click on "Show All Files" and right-click to delete.

Deleting Existing mdf File

Step 6: Open the Package Manager Console and execute the following commands one by one:

  • Enable-Migrations
  • Add-Migration Init
  • Update-Database

Step 7: Run the application and log in using Facebook and Google.

Fb Registeration in Mvc App

Step 8: Now examine the table again.

Updated Users Table

That's it.

Summary

This article will help you to create the MVC Web application and enable users to log in using OAuth 2.0 and OpenID with their user credentials. Thanks for reading.