Adding Identity On Web Page In ASP.NET

Introduction

In this article I will tell you about how to add ASP.NET Identity to an empty or existing web forms project. I will outline all the Nuget Packages you need to install, and classes you need to add.

Description

Firstly, we will learn what is ASP.NET Identity and why we use them.

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

Goals of ASP.NET Identity:
  • One 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 how to use ASP.NET Identity to an empty and existing Web forms project.

  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# in the left side, then Web and then select ASP.NET Web application. Name your project ”AspWebFormsIdentity” and click OK.

    starapps

  4. In the New ASP.NET Project dialog, we select the Empty template and then click OK.

selectempty

You can see the Change Authentication button is disabled because in this empty template no authentication support is provided. The Web Forms, MVC, and Web API template allow you to select the authentication mode as shown below.

openauth

You can Add Identity Packages to App

Go to the Solution Explorer, right-click your project and select Manage NuGet Packages...


openNuGet

In the search text box dialog, type ”identity" and click Install for this package.

identity

Install other authentication package to your application


otheridentity

After that Adding the forms to create users

  1. Go to solution explorer, right click project and click add and then Web form.

    wenform

  2. In the Specify Name for item, name the web form Register, and click OK.

  3. Register.aspx file with the code below,
    1. <%@pageLanguage="C#"AutoEventWireup="true"CodeBehind="Register.aspx.cs"Inherits="AspWebFormsIdentity.Register”%>  
    2.     <!DOCTYPEhtml>  
    3.     <htmlxmlnshtmlxmlns="http://www.w3.org/1979/xhtml">  
    4.   
    5.         <head runat="server">  
    6.             <title>My Web Forms Identity </title>  
    7.         </head>  
    8.   
    9.         <body>  
    10.             <form id="form1" runat="server">  
    11.                 <div>  
    12.                     <h4> Create a new user</h4>  
    13.                     <hr/>  
    14.                     <p>  
    15.                         <asp:Literal runat="server" ID="StatusMessage" /> </p>  
    16.                     <div>  
    17.                         <asp:Label runat="server" ID="UserName">User name</asp:Label>  
    18.                         <div>  
    19.                             <asp:TextBox runat="server" ID="UserName" /> </div>  
    20.                     </div>  
    21.                     <div>  
    22.                         <asp:Label runat="server" ID="Password">Password</asp:Label>  
    23.                         <div>  
    24.                             <asp:TextBox runat="server" ID="Password" TextMode="Password" /> </div>  
    25.                     </div>  
    26.                     <div>  
    27.                         <asp:Label runat="server" ID="ConfirmPassword">Confirm Password</asp:Label>  
    28.                         <div>  
    29.                             <asp:TextBox runat="server" ID="ConfirmPassword" TextMode="Password" /> </div>  
    30.                     </div>  
    31.                     <div>  
    32.                         <div>  
    33.                             <asp:Button runat="server" OnClick="CreateUser_Click" Text="Register" /> </div>  
    34.                     </div>  
    35.                 </div>  
    36.             </form>  
    37.         </body>  
    38.   
    39.         </html>  
  4. Now open the Register.aspx.cs file and replace the contents of the file with the following code.
    1. using System;  
    2. using System.Collections.Generic;  
    3. using System.Linq;  
    4. using System.Web;  
    5. using System.Web.UI;  
    6. using System.Web.UI.WebControls;  
    7. using Microsoft.AspNet.Identity;  
    8. using Microsoft.AspNet.Identity.EntityFramework;  
    9. namespace AspWebFormsIdentity  
    10. {  
    11.     public partial class Register: System.Web.UI.Page  
    12.     {  
    13.         protected void Page_Load(object sender, EventArgs e)  
    14.         {}  
    15.         protected void CreateUser_Click(object sender, EventArgs e)  
    16.         {  
    17.             var userStore = new UserStore < IdentityUser > ();  
    18.             var manager = new UserManager < IdentityUser > (userStore);  
    19.             var user = new IdentityUser()  
    20.             {  
    21.                 UserName = UserName.Text  
    22.             };  
    23.             IdentityResult result = manager.Create(user, Password.Text);  
    24.             if (result.Succeeded)  
    25.             {  
    26.                 StatusMessage.Text = string.Format("User {0} was created successfully!", user.UserName);  
    27.             }  
    28.             else  
    29.             {  
    30.                 StatusMessage.Text = result.Errors.FirstOrDefault();  
    31.             }  
    32.         }  
    33.     }  
    34. }  
  5. Go to Solution Explorer, right-click your project and click Add, Add ASP.NET folder and then App_Data.

    addapp

  6. Open the Web.config file and add a connection string. The database will be created at runtime by EntityFramework for the Identity entities. 
    1. <?xmlversion="1.0"encoding="utf-8"?>  
    2.     <configuration>  
    3.         <configSections>  
    4.             <sectionname="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e08" requirePermission="false" /> </configSections>  
    5.         <connectionStrings>  
    6.             <addname="MalikData" connectionString="Data Source=(LocalDb)\v11.0;AttachDbFilename=|DataDirectory|\AspWebFormsIdentity.mdf;Initial      Catalog=aspmem; uid=sa; password=Password$2" providerName="System.Data.SqlClient" /> </connectionStrings>  
    7.         <system.web>  
    8.             <compilationdebug="true" targetFramework="4.5" />  
    9.             <httpRuntimetargetFramework="4.5" /> </system.web>  
    10.         <entityFramework>  
    11.             <defaultConnectionFactorytype="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">  
    12.                 <parameters>  
    13.                     <parametervalue="v11.0" /> </parameters>  
    14.                 </defaultConnectionFactory>  
    15.                 <providers>  
    16.                     <providerinvariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" /> </providers>  
    17.         </entityFramework>  
    18.     </configuration>  
  7. Go to the Register.aspx andright click file Register.aspx in your project and select Set As Start Page.

    setpage

Press Ctrl + F5 to build and run the web application. Enter a new user name password and confirm Password and then click Register.

createuser

Show the LocalDataBase Identity Database and Tables created by Entity Framework.

Go to the VIEW menu and click Server Explorer,

serverex

Click on DefaultConnection expand Tables, right click AspNetUsers and click Show Table Data.

showdata

tabledata 

Now We Can Add OWIN Startup and Authentication Configuration Classes

  1. Go to the Solution Explorer, Right-click your project, click Add, and then Add New Item and click Add. 

    sturt

  2. Now in the Startup.cs file, write the following code to configure OWIN cookie authentication.
    1. using Microsoft.AspNet.Identity;  
    2. using Microsoft.Owin;  
    3. using Microsoft.Owin.Security.Cookies;  
    4. using Owin;  
    5. [assembly: OwinStartup(typeof(WebFormsIdentity.Startup))]  
    6. namespace WebFormsIdentity  
    7. {  
    8.     public class Startup  
    9.     {  
    10.         public void Configuration(IAppBuilder app)  
    11.         {  
    12.             app.UseCookieAuthentication(new CookieAuthenticationOptions  
    13.             {  
    14.                 Authentication Type = DefaultAuthenticationTypes.ApplicationCookie,  
    15.                     LoginPath = new PathString("Login")  
    16.             });  
    17.         }  
    18.     }  
    19. }  

Now web forms for Registering and Logging User

  1. Open the Register.cs file and add the following code which will log in the user when registration succeed.
    1. using Microsoft.AspNet.Identity;  
    2. using Microsoft.AspNet.Identity.EntityFramework;  
    3. using Microsoft.Owin.Security;  
    4. using System;  
    5. using System.Linq;  
    6. using System.Web;  
    7. namespace WebFormsIdentity  
    8. {  
    9.     publicpartialclassRegister: System.Web.UI.Page  
    10.     {  
    11.         protected void CreateUser_Click(object sender, EventArgs e)  
    12.         {  
    13.             var userStore = new UserStore < IdentityUser > ();  
    14.             var manager = new UserManager < IdentityUser > (userStore);  
    15.             var user = new IdentityUser()  
    16.             {  
    17.                 UserName = UserName.Text  
    18.             };  
    19.             IdentityResult result = manager.Create(user, Password.Text);  
    20.             if (result.Succeeded)  
    21.             {  
    22.                 var authenticationManager = HttpContext.Current.GetOwinContext().Authentication;  
    23.                 var userIdentity = manager.CreateIdentity(user, DefaultAuthenticationTypes.ApplicationCookie);  
    24.                 authenticationManager.SignIn(new AuthenticationProperties()  
    25.                 {}, userIdentity);  
    26.                 Response.Redirect("~/Login.aspx");  
    27.             }  
    28.             else  
    29.             {  
    30.                 StatusMessage.Text = result.Errors.FirstOrDefault();  
    31.             }  
    32.         }  
    33.     }  
    34. }  
  2. Go to solution explorer, right click project, click add and then Web form for login,

    addfrm

  3. Copy and paste the code of Login.aspx file with the following code,
    1. <%@PageLanguage="C#" AutoEventWireup="true" CodeBehind="Login.aspx.cs" Inherits=" AspWebFormsIdentity.Login"%>  
    2.     <!DOCTYPEhtml>  
    3.     <htmlxmlnshtmlxmlns="http://www.w3.org/1979/xhtml">  
    4.   
    5.         <head runat="server">  
    6.             <title> Login Form </title>  
    7.         </head>  
    8.   
    9.         <body>  
    10.             <form id="form1" runat="server">  
    11.                 <div>  
    12.                     <h4>Log In</h4>  
    13.                     <hr/>  
    14.                     <p>  
    15.                         <asp:Literal runat="server" ID="StatusText" /> </p>  
    16.                     <div>  
    17.                         <asp:Label runat="server" AssociatedControl ID="UserName">User name</asp:Label>  
    18.                         <div>  
    19.                             <asp:TextBox runat="server" ID="UserName" /> </div>  
    20.                     </div>  
    21.                     <div>  
    22.                         <asp:Label runat="server" AssociatedControl ID="Password">Password</asp:Label>  
    23.                         <div>  
    24.                             <asp:TextBox runat="server" ID="Password" TextMode="Password" /> </div>  
    25.                     </div>  
    26.                     <div>  
    27.                         <div>  
    28.                             <asp:Button runat="server" OnClick="SignIn" Text="Log in" /> </div>  
    29.                     </div>  
    30.                     <div>  
    31.                         <asp:Button runat="server" OnClick="SignOut" Text="Log out" /> </div>  
    32.                 </div>  
    33.             </form>  
    34.         </body>  
    35.   
    36.         </html>  
  4. Copy and paste the code of Login.aspx.cs file with the following code,
    1. using Microsoft.AspNet.Identity;  
    2. using Microsoft.AspNet.Identity.EntityFramework;  
    3. using Microsoft.Owin.Security;  
    4. using System;  
    5. using System.Web;  
    6. using System.Web.UI.WebControls;  
    7. namespace WebFormsIdentity  
    8. {  
    9.     public partial class Login: System.Web.UI.Page  
    10.     {  
    11.         protected void Page_Load(object sender, EventArgs e)  
    12.         {  
    13.             if (!IsPostBack)  
    14.             {  
    15.                 if (User.Identity.IsAuthenticated)  
    16.                 {  
    17.                     StatusText.Text = string.Format("Hello {0}!!", User.Identity.GetUserName());  
    18.                     LoginStatus.Visible = true;  
    19.                     LogoutButton.Visible = true;  
    20.                 }  
    21.                 else  
    22.                 {  
    23.                     LoginForm.Visible = true;  
    24.                 }  
    25.             }  
    26.         }  
    27.         protectedvoid SignIn(object sender, EventArgs e)  
    28.         {  
    29.             var userStore = new UserStore < IdentityUser > ();  
    30.             var userManager = new UserManager < IdentityUser > (userStore);  
    31.             var user = userManager.Find(UserName.Text, Password.Text);  
    32.             if (user != null)  
    33.             {  
    34.                 var authenticationManager = HttpContext.Current.GetOwinContext().Authentication;  
    35.                 var userIdentity = userManager.CreateIdentity(user, DefaultAuthenticationTypes.ApplicationCookie);  
    36.                 authenticationManager.SignIn(new AuthenticationProperties()  
    37.                 {  
    38.                     IsPersistent = false  
    39.                 }, userIdentity);  
    40.                 Response.Redirect("~/Login.aspx");  
    41.             }  
    42.             else  
    43.             {  
    44.                 StatusText.Text = "Invalid username or password.";  
    45.                 LoginStatus.Visible = true;  
    46.             }  
    47.         }  
    48.         protectedvoid SignOut(object sender, EventArgs e)  
    49.         {  
    50.             var authenticationManager = HttpContext.Current.GetOwinContext().Authentication;  
    51.             authenticationManager.SignOut();  
    52.             Response.Redirect("~/Login.aspx");  
    53.         }  
    54.     }  
    55. }  

Press Ctrl + F5 or F5 to run the web application. Enter a new user name password.

login

Note:

  • Click on log out button and you will be redirected to the login form
  • Enter the invalid username or password and click login button.
  • The usermanager.find will return the invalid username or password.

invaliduser


Similar Articles