Authentication Services With ASP.NET MVC Web Application

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.
  1. Go to the Start and run Visual Studio 2013 for Web.

  2. Click new project from the start page or go to the menu and select file and then New project.

  3. Select Visual C# on the left side, then Web and then select ASP.NET Web Application. Name your project ”AspWebFormsIdentity” and click OK.

    startApp

  4. After that we select the MVC Project Template to create the Application and then Click OK

    selectMVC

    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.

    authenticationmode

  5. When we click on "OK" the MVC application is created automatically. Now open the layout file.

    layout

  6. After that change the application name and title as shown below:
  1. <!DOCTYPE html>  
  2. <html>  
  3.   
  4. <head>  
  5.     <meta charset="utf-8" />  
  6.     <meta name="viewport" content="width=device-width, initial-scale=1.0">  
  7.     <title>@ViewBag.Title - Asp.Net Identity App </title>  
  8.     @Styles.Render("~/Content/css") @Scripts.Render("~/bundles/modernizr")  
  9.   
  10. </head>  
  11.   
  12. <body>  
  13.     <div class="navbar navbar-inverse navbar-fixed-top">  
  14.         <div class="container">  
  15.             <div class="navbar-header">  
  16.                 <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">  
  17.                     <span class="icon-bar"></span>  
  18.                     <span class="icon-bar"></span>  
  19.                     <span class="icon-bar"></span>  
  20.                 </button>  
  21.                 @Html.ActionLink("AspIdentityAuthentication", "Index", "Home", new { area = "" }, new { @class = "navbar-brand" })  
  22.             </div>  
  23.             <div class="navbar-collapse collapse">  
  24.                 <ul class="nav navbar-nav">  
  25.                     <li>@Html.ActionLink("Home", "Index", "Home")</li>  
  26.                     <li>@Html.ActionLink("About", "About", "Home")</li>  
  27.                     <li>@Html.ActionLink("Contact", "Contact", "Home")</li>  
  28.                 </ul>  
  29.                 @Html.Partial("_LoginPartial")  
  30.             </div>  
  31.         </div>  
  32.     </div>  
  33.     <div class="container body-content">  
  34.         @RenderBody()  
  35.         <hr />  
  36.         <footer>  
  37.             <p>© @DateTime.Now.Year - Asp.Net Identity App </p>  
  38.         </footer>  
  39.     </div>  
  40.   
  41.     @Scripts.Render("~/bundles/jquery") @Scripts.Render("~/bundles/bootstrap") @RenderSection("scripts", required: false)  
  42. </body>  
  43.   
  44. </html>  

        7. Now run the application by pressing F5 or Ctrl+F5.

runlayout



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:

 
newgoogle
 
  1. After that Click on Create Button, the following window will be visible,

    GDC


    gdc2

  2. After clicking on the OAuth 2.0 Client ID, the following window will be visible,

    gdc3

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

    gdc4

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

    googleid

Now we'll enable the Google authentication for the application using the Client ID, Client secret and the following procedure,

  1. Now we'll ppen the Startup_Auth.cs file for enabling the authentication.

    startup

  2. Now Uncomment the code to enable Google Authentication as in the following code,
    1. // Uncomment the following lines to enable logging in with third party login providers    
    2. //app.UseMicrosoftAccountAuthentication(    
    3. // clientId: "",    
    4. // clientSecret: "");    
    5. //app.UseTwitterAuthentication(    
    6. // consumerKey: "",    
    7. // consumerSecret: "");    
    8. //app.UseFacebookAuthentication(    
    9. // appId: "",    
    10. // appSecret: "");    
    11. app.UseGoogleAuthentication(new GoogleOAuth2AuthenticationOptions()  
    12. {  
    13.     ClientId = "****************************",  
    14.         ClientSecret = "*********************"  
    15. });  
  3. After that run the Application and click on the Login Button

    googlebtn

  4. Click on "Google",

    logimid

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

    googleallow

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

    registoridd

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

    hellousers 
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.
  1. In the browser navigate to https://developers.facebook.com/?ref=pf and log in by the Facebook Credentials.

  2. On the Apps tab, click Create New App.

    fbcreate

  3. Enter the App Name and select the Category. After that click Create App ID.

    fbappcreate

  4. Submit the standard Security Check.

    securitycheck

  5. You can now create the AppID and App Secret. Also, you can show the App Secret by clicking on the Show button.

    appidshow

  6. After that click on the Settings section of the page select and Add Platform to specify that you are adding a website application.

    addptfrm

  7. Select Website from the platform choice.

    selectwebsite

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

    addurl

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,

  1. // Uncomment the following lines to enable logging in with third party login providers  
  2. //app.UseMicrosoftAccountAuthentication(  
  3. // clientId: "",  
  4. // clientSecret: "");  
  5. //app.UseTwitterAuthentication(  
  6. // consumerKey: "",  
  7. // consumerSecret: "");  
  8. app.UseFacebookAuthentication(  
  9.     appId: "*********************",  
  10.     appSecret: "*******************");  
  11.   
  12. app.UseGoogleAuthentication(new GoogleOAuth2AuthenticationOptions() {  
  13.     ClientId = "********************************",  
  14.         ClientSecret = "*****************************"  
  15. });  
Step 3: After that Run the Application and Click on the Facebook Login Button.
fblogin

 Step 4: Now you will be prompted to permission for the application to access your public profile.

aspouth


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.

 hellousers

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.
  1. Select the project in the Solution Explorer and press F4 to open the properties.
  2. Enable SSL to true and copy the SSL URL.

    sslurl

  3. After that right-click on the project to open the properties.

  4. Click the web tab and in the Project URL, paste the SSL URL as shown below:

    weburl

  5. Now Save and we will need this URL to configure the Facebook App.
Membership Information in MVC App
  1. In the VIEW menu, click Server Explorer,

    se

  2. Expand DefaultConnection expand Tables, right click AspNetUsers and click Show Table Data.

    showdata

    datauser
We Can Add More Profile Data:
  1. Firstly, we will open the Models\IdentityModels.cs file and modify the code with the following highlight code as in the following,
    1. Using System;  
    2.   
    3. namespace MvcSocialAuthentication.Models 
    4. {  
    5.     public class ApplicationUser: IdentityUser 
    6. {  
    7.         Public string City 
    8.         {  
    9.             get;  
    10.             Set;  
    11.         }  
    12.   
    13.         public DateTime ? DateOfBorth 
    14.         {  
    15.             get;  
    16.             set;  
    17.         }  
    18.     }  
    19.   
    20.     public class ApplicationDbContext: IdentityDbContext < ApplicationUser >  
    21.    {  
    22.         public ApplicationDbContext(): base("DefaultConnection") {}  
    23.     }  
    24. }  
  2. Now open the Models\AccountViewModels.cs file and modify the code with the highlighted code below:
    1. using System;  
    2. using System.Collections.Generic;  
    3. using System.ComponentModel.DataAnnotations;  
    4.   
    5. namespace AspWebFromsIdentity.Models  
    6. {  
    7.         public class ExternalLoginConfirmationViewModel  
    8.         {  
    9.             [Required]  
    10.             [Display(Name = "Email")]  
    11.             public string UserName   
    12.             {  
    13.                 get;  
    14.                 set;  
    15.             }  
    16.             public string City  
    17.             {  
    18.                 get;  
    19.                 set;  
    20.             }  
    21.             [Display(Name = "Birth Date")]  
    22.             public DateTime ? DateofBirth  
    23.             {  
    24.                 get;  
    25.                 set;  
    26.             }  
    27.   
    28.             public string Email  
    29.             {  
    30.                 get;  
    31.                 set;  
    32.             }  
    33.         }  
  3. Open the Controllers\AcountController.cs file and modify the code with the highlighted code below:
    1. public async Task < ActionResult > ExternalLoginConfirmation(ExternalLoginConfirmationViewModel model, string returnUrl)  
    2. {  
    3.     if (User.Identity.IsAuthenticated)  
    4.     {  
    5.         return RedirectToAction("Index""Manage");  
    6.     }  
    7.   
    8.     if (ModelState.IsValid)  
    9.     {  
    10.         // Get the information about the user from the external login provider    
    11.         var info = await AuthenticationManager.GetExternalLoginInfoAsync();  
    12.         if (info == null) {  
    13.             return View("ExternalLoginFailure");  
    14.         }  
    15.         var user = new ApplicationUser  
    16.         {  
    17.             UserName = model.Email,  
    18.                 Email = model.Email,  
    19.                 City = model.City,  
    20.                 DateofBirth = model.DateofBirth  
    21.         };  
    22.         var result = await UserManager.CreateAsync(user);  
    23.         if (result.Succeeded)  
    24.         {  
    25.             result = await UserManager.AddLoginAsync(user.Id, info.Login);  
    26.             if (result.Succeeded)   
    27.             {  
    28.                 await SignInManager.SignInAsync(user, isPersistent: false, rememberBrowser: false);  
    29.                 return RedirectToLocal(returnUrl);  
    30.             }  
    31.         }  
    32.   
    33.         AddErrors(result);  
    34.     }  
    35.   
    36.     ViewBag.ReturnUrl = returnUrl;  
    37.     return View(model);  
    38. }  
  4. Open the Views\Account\ExternalLoginConfirmation.cshtml file and modify the code with the highlighted code below:
    1. @using(Html.BeginForm("ExternalLoginConfirmation", "Account", new {  
    2.         ReturnUrl = ViewBag.ReturnUrl  
    3.     }, FormMethod.Post, new {  
    4.         @class = "form-horizontal"role = "form"  
    5.     })) {  
    6.         @Html.AntiForgeryToken()  
    7.   
    8.         < h4 > Association Form < /h4>  < hr / >  
    9.             @Html.ValidationSummary(true, "", new {  
    10.                 @class = "text-danger"  
    11.             })  
    12.           < p class = "text-info" >  
    13.   
    14.             You 've successfully authenticated with <strong>@ViewBag.LoginProvider</strong>.  
    15.         Please enter a user name  
    16.         for this site below and click the Register button to finish  
    17.         logging in . < /p> 
    18.         < div class = "form-group" >  
    19.         @Html.LabelFor(m => m.Email, new {  
    20.                 @class = "col-md-2 control-label"  
    21.             }) < div class = "col-md-10" >  
    22.             @Html.TextBoxFor(m => m.Email, new {  
    23.                 @class = "form-control"  
    24.             })  
    25.         @Html.ValidationMessageFor(m => m.Email, "", new {  
    26.                 @class = "text-danger"  
    27.             }) < /div> < /div > < div class = "form-group" >  
    28.             @Html.LabelFor(m => m.City, new {  
    29.                 @class = "col-md-2 control-label"  
    30.             }) < div class = "col-md-10" >  
    31.             @Html.TextBoxFor(m => m.City, new {  
    32.                 @class = "form-control"  
    33.             })  
    34.         @Html.ValidationMessageFor(m => m.City) < /div>  
    35.           < /div>   
    36.           < div class = "form-group" >  
    37.             @Html.LabelFor(m => m.DateofBirth, new {  
    38.                 @class = "col-md-2 control-label"  
    39.             }) < div class = "col-md-10" >  
    40.             @Html.TextBoxFor(m => m.DateofBirth, new {  
    41.                 @class = "form-control"  
    42.             })  
    43.         @Html.ValidationMessageFor(m => m.DateofBirth)   
    44.             < /div>   
    45.           < /div>  

 Step 1. Go to the menu tools and open the Package Manager Console and execute the following commands one by one:

               nuget

 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,

           enable


After that we execute the second command Add-Migration Init as in the following windows,
 
             addmig

Finally execute the last Command Update-database.

            updatedata

 Step 3. Now run the application and log in using Google.
 logingoogle


 Step 4. Again Expand DefaultConnection expand Tables, right click AspNetUsers and click Show Table Data.

dob

X

Build smarter apps with Machine Learning, Bots, Cognitive Services - Start free.

Start Learning Now