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".
Step 2: Select the ASP.NET Web application and provide a name.
Step 3: In the next wizard select the MVC Project Template to create the application.
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.
Step 5: Now modify the application name and title as shown below:
Step 6: Press Ctrl+F5 or F5 to run the application.
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
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".
Step 4: In the Login page click on "Google".
Step 5: Enter the credentials for Google Account and you'll be prompted to authenticate the Localhost.
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.
Step 7: Now you will be logged in with Google. Check it out
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.
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:
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".
Step 3: Enter the App name and namespace and choose "Category".
Step 4: Now click on "Add Platform".
Step 5: Select the Website platform.
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".
Step 7: Now again open the Startup_Auth.cs file and paste in the App ID and App Secret value as shown below:
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.
Step 9: Click on "Login" and use the Facebook service to login.
Step 10: Now enter the Facebook credentials to log in with Facebook.
Now you will be prompted to grant the permission for the app to access the profile and friends list.
Step 11: Now register and associate the Facebook account.
Step 12: Now you will be logged in with Facebook. Check it out.
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.
All users are shown in the table as shown below:
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.
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.
Step 8: Now examine the table again.
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.