Introduction
In this article I will tell you how to use External Authentication Services with ASP.NET MVC Web Application. I will outline all the Nuget Packages you need to install, and classes you need to add.
ASP.NET Identity
The ASP.NET Identity model is way more flexible than the old membership system.
ASP.NET Identity is the new membership system for building ASP.NET web application. ASP.NET allows you to add login features to your application and makes it easy to customize data about the logged in user.
ASP.NET Identity can be used with all the ASP.NET framework such as ASP.NET MVC, Web Forms, Web Pages, Web API and SignalR.
Goals of ASP.NET Identity:
ASP.NET membership story-web APIs and Web Apps.
- Profile.
- Extensibility allows for non SQL persistence Model.
- Improve unit testability of application code.
- Separate Authentication from membership.
- Full support for Async programming.
- claims Based.
- Roles.
Now we will do the step by step process.
- Go to the Start and run Visual Studio 2013 for Web.
- Click new project from the start page or go to the menu and select file and then New project.
- Select Visual C# on the left side, then Web and then select ASP.NET Web Application. Name your project ”AspWebFormsIdentity” and click OK.
- After that we select the MVC Project Template to create the Application and then Click OK.
Note: The Web Forms, MVC and Web API templates allow you to select the authentication approach but when we select Empty the Change Authentication button is disabled and no authentication support.
- When we click on "OK" the MVC application is created automatically. Now open the layout file.
- After that change the application name and title as shown below:
- <!DOCTYPE html>
- <html>
-
- <head>
- <meta charset="utf-8" />
- <meta name="viewport" content="width=device-width, initial-scale=1.0">
- <title>@ViewBag.Title - Asp.Net Identity App </title>
- @Styles.Render("~/Content/css") @Scripts.Render("~/bundles/modernizr")
-
- </head>
-
- <body>
- <div class="navbar navbar-inverse navbar-fixed-top">
- <div class="container">
- <div class="navbar-header">
- <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
- <span class="icon-bar"></span>
- <span class="icon-bar"></span>
- <span class="icon-bar"></span>
- </button>
- @Html.ActionLink("AspIdentityAuthentication", "Index", "Home", new { area = "" }, new { @class = "navbar-brand" })
- </div>
- <div class="navbar-collapse collapse">
- <ul class="nav navbar-nav">
- <li>@Html.ActionLink("Home", "Index", "Home")</li>
- <li>@Html.ActionLink("About", "About", "Home")</li>
- <li>@Html.ActionLink("Contact", "Contact", "Home")</li>
- </ul>
- @Html.Partial("_LoginPartial")
- </div>
- </div>
- </div>
- <div class="container body-content">
- @RenderBody()
- <hr />
- <footer>
- <p>© @DateTime.Now.Year - Asp.Net Identity App </p>
- </footer>
- </div>
-
- @Scripts.Render("~/bundles/jquery") @Scripts.Render("~/bundles/bootstrap") @RenderSection("scripts", required: false)
- </body>
-
- </html>
7. Now run the application by
pressing F5 or Ctrl+F5.
Google Authentication
The first service I wanted to login with was Google. I need to head over to the Google Developers Console and create a new project and a new app. Selecting to create an app comes up with a modal dialog, which asks for a bit of information:
- After that Click on Create Button, the following window will be visible,
- After clicking on the OAuth 2.0 Client ID, the following window will be visible,
- Once there, we’re going to create a new Client ID, of course this is of type “Web Application”, and then simply fill out the details, mine looked like this.
- Once created, Google then provides us with a Client ID and Client Secret, this is what we need for our project. As the commented out code stub in the Startup.
Now we'll enable the Google authentication for the application using the Client ID, Client secret and the following procedure,
Facebook Authentication
Next up, Facebook! Similarly to Google, I need to head over to the Facebook Developers Site and create a new project, this was a little simpler than Google version.
- In the browser navigate to https://developers.facebook.com/?ref=pf and log in by the Facebook Credentials.
- On the Apps tab, click Create New App.
- Enter the App Name and select the Category. After that click Create App ID.
- Submit the standard Security Check.
- You can now create the AppID and App Secret. Also, you can show the App Secret by clicking on the Show button.
- After that click on the Settings section of the page select and Add Platform to specify that you are adding a website application.
- Select Website from the platform choice.
- Note your App ID and your App Secret so that you can add both into your MVC application. Also, Add your Site URL (https://localhost:44303/) to test your MVC application. Also, add a Contact Email, then select Save Changes.
Step 1: Now we'll Open the Startup_Auth.cs file for enabling the authentication.
Step 2: Now Uncomment the code to enable Facebook Authentication and copy and past the app Id, and App Secret as in the following code,
- // Uncomment the following lines to enable logging in with third party login providers
- //app.UseMicrosoftAccountAuthentication(
- // clientId: "",
- // clientSecret: "");
- //app.UseTwitterAuthentication(
- // consumerKey: "",
- // consumerSecret: "");
- app.UseFacebookAuthentication(
- appId: "*********************",
- appSecret: "*******************");
-
- app.UseGoogleAuthentication(new GoogleOAuth2AuthenticationOptions() {
- ClientId = "********************************",
- ClientSecret = "*****************************"
- });
Step 3: After that Run the Application and Click on the
Facebook Login Button.
Step 4: Now you will be prompted to permission for the application to access your public profile.
Step 5. Now you will be
redirected back to the Register page and enter the user name to register.
Step 6. Now you will be logged in with facebook. Check it out.
Now 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.
- Select the project in the Solution Explorer and press F4 to open the properties.
- Enable SSL to true and copy the SSL URL.
- After that right-click on the project to open the properties.
- Click the web tab and in the Project URL, paste the SSL URL as shown below:
- Now Save and we will need this URL to configure the Facebook App.
Membership Information in MVC App
- In the VIEW menu, click Server Explorer,
- Expand DefaultConnection expand Tables, right click AspNetUsers and click Show Table Data.
We Can Add More Profile Data:
- Firstly, we will open the Models\IdentityModels.cs file and modify the code with the following highlight code as in the following,
- Using System;
-
- namespace MvcSocialAuthentication.Models
- {
- public class ApplicationUser: IdentityUser
- {
- Public string City
- {
- get;
- Set;
- }
-
- public DateTime ? DateOfBorth
- {
- get;
- set;
- }
- }
-
- public class ApplicationDbContext: IdentityDbContext < ApplicationUser >
- {
- public ApplicationDbContext(): base("DefaultConnection") {}
- }
- }
- Now open the Models\AccountViewModels.cs file and modify the code with the highlighted code below:
- using System;
- using System.Collections.Generic;
- using System.ComponentModel.DataAnnotations;
-
- namespace AspWebFromsIdentity.Models
- {
- public class ExternalLoginConfirmationViewModel
- {
- [Required]
- [Display(Name = "Email")]
- public string UserName
- {
- get;
- set;
- }
- public string City
- {
- get;
- set;
- }
- [Display(Name = "Birth Date")]
- public DateTime ? DateofBirth
- {
- get;
- set;
- }
-
- public string Email
- {
- get;
- set;
- }
- }
- 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("Index", "Manage");
- }
-
- if (ModelState.IsValid)
- {
-
- var info = await AuthenticationManager.GetExternalLoginInfoAsync();
- if (info == null) {
- return View("ExternalLoginFailure");
- }
- var user = new ApplicationUser
- {
- UserName = model.Email,
- Email = model.Email,
- City = model.City,
- DateofBirth = model.DateofBirth
- };
- var result = await UserManager.CreateAsync(user);
- if (result.Succeeded)
- {
- result = await UserManager.AddLoginAsync(user.Id, info.Login);
- if (result.Succeeded)
- {
- await SignInManager.SignInAsync(user, isPersistent: false, rememberBrowser: false);
- return RedirectToLocal(returnUrl);
- }
- }
-
- AddErrors(result);
- }
-
- ViewBag.ReturnUrl = returnUrl;
- return View(model);
- }
- Open the Views\Account\ExternalLoginConfirmation.cshtml file and modify the code with the highlighted code below:
- @using(Html.BeginForm("ExternalLoginConfirmation", "Account", new {
- ReturnUrl = ViewBag.ReturnUrl
- }, FormMethod.Post, new {
- @class = "form-horizontal", role = "form"
- })) {
- @Html.AntiForgeryToken()
-
- < h4 > Association Form < /h4> < hr / >
- @Html.ValidationSummary(true, "", new {
- @class = "text-danger"
- })
- < p class = "text-info" >
-
- You 've successfully authenticated with <strong>@ViewBag.LoginProvider</strong>.
- Please enter a user name
- for this site below and click the Register button to finish
- logging in . < /p>
- < div class = "form-group" >
- @Html.LabelFor(m => m.Email, new {
- @class = "col-md-2 control-label"
- }) < div class = "col-md-10" >
- @Html.TextBoxFor(m => m.Email, new {
- @class = "form-control"
- })
- @Html.ValidationMessageFor(m => m.Email, "", new {
- @class = "text-danger"
- }) < /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>
Step 1. Go to the menu tools and open the
Package Manager Console and execute the following commands one by one:
Step 2. Now Run the following command.
- Enable-Migrations.
- Add-Migration Init.
- Update-Database.
Firstly we execute the Enable-Migrations Command and Show windows as in the following,
After that we execute the second command Add-Migration Init as in the following windows,
Finally execute the last Command Update-database.
Step 3. Now run the application and log in using Google.
Step 4. Again Expand DefaultConnection expand Tables, right click AspNetUsers and click Show Table Data.