Working With ASP.Net Identity in Empty Project in Visual Studio 2013

Introduction

Today, in this article you will see the process of adding an ASP.NET Identity to the ASP.NET Web Application developed in the Empty Project Template. Since I already introduced the Introduction of ASP.NET Identity in Visual Studio 2013, so here in this article I am creating an Empty Web Application in Visual Studio 2013 and adding the ASP.NET Identity into it.

There are various project templates defined in Visual Studio 2013 and when you create an application with the help of those templates like MVC, Web Forms and so on, Visual Studio installs all the required references and necessary classes in the project. Here in this article, the LocalDB is used for the SQL Database.

So, let's begin to work with ASP.NET Identity using the following sections:

  • Project Implementation
  • Working with LocalDB
  • Configure the OWIN Authentication

Project Implementation

Use the following procedure to create the ASP.NET application with an Empty Project in Visual Studio 2013.

Step 1: Open Visual Studio 2013.

Step 2: Click on "New Project".

Create Project in VS 2013

Step 3: In the ONE ASP.NET Wizard, please select an Empty Project Template

Empty Project in VS 2013

You will notice that the Change Authentication is disabled because it is an empty project. You can the change authentication for the MVC, Web Forms and other templates.

Add ASP.NET Identity

It is an empty project template, therefore we need to add the ASP.NET Identity package to this project using the following procedure.

Step 4: In your Solution Explorer, just right-click on your project and click on "Manage NuGet Packages".

Manage NuGet in Project

Step 5: Enter identity.E in the Search box and click on Enter to install this package.

Identity in NuGet

This package will install the Entity Framework 6 and the ASP.NET Identity Core.

Add Web Forms

Use the following procedure to add a Web Form to this project.

Step 6: Click on your project to add a New Web Form named Registration.

Adding Web Form

Step 7: Replace the body content with the following code:

<form id="form1" runat="server">

   <div>User Registration</div>

   <br />

   <br />

   <div class="rowone" style="width: 300px; height: 40px;">

       <div class="username" style="float: left; overflow: hidden;">

           <asp:Label ID="LblUsername" runat="server" Text="User Name"></asp:Label>

       </div>

       <div class="usernameinput" style="float: right; overflow: hidden;">

           <asp:TextBox ID="TxtUserName" runat="server"></asp:TextBox>

       </div>

   </div>

   <div class="rowone" style="width: 300px; height: 40px;">

       <div class="userpwd" style="float: left; overflow: hidden;">

           <asp:Label ID="LblUserPwd" runat="server" Text="User Password"></asp:Label>

            </div>

       <div class="userpwdinput" style="float: right; overflow: hidden;">

           <asp:TextBox ID="TxtUserPassword" runat="server"></asp:TextBox>

       </div>

   </div>

   <div class="rowone" style="width: 300px; height: 40px;">

       <div class="userconpwd" style="float: left; overflow: hidden;">

           <asp:Label ID="LblConPwd" runat="server" Text="Confirm Password"></asp:Label>

       </div>

       <div class="userconpwdinput" style="float: right; overflow: hidden;">

           <asp:TextBox ID="TxtConfirmPassword" runat="server"></asp:TextBox>

       </div>

   </div>

   <div class="rowone" style="width: 300px; height: 40px;">

       <div class="userreg" style="float: left; overflow: hidden;">

           <asp:Button ID="BtnRegister" runat="server" Text="Register" OnClick="UserRegistration_Click" />

       </div>

       <div class="userpwdinput" style="float: right; overflow: hidden;">

           <asp:Label ID="LblMessage" runat="server"></asp:Label>

       </div>

   </div>

</form>

Step 8: Open the Code Behind of Registration.aspx and modify the UserRegistration_Click event with the following code:

Note: Please add the following assembly to your class:

using Microsoft.AspNet.Identity;

using Microsoft.AspNet.Identity.EntityFramework;

Now modify the event:

protected void UserRegistration_Click(object sender, EventArgs e)

{

    Register_User();           

}

 

void Register_User()

{

    var User_Store = new UserStore<IdentityUser>();

    var User_Manager = new UserManager<IdentityUser>(User_Store);

   

    var New_User = new IdentityUser() { UserName = TxtUserName.Text };

    IdentityResult User_Result = User_Manager.Create(New_User, TxtUserPassword.Text);

   

    if (User_Result.Succeeded)

    {

       LblMessage.Text = string.Format("User {0} Registered Successfully", New_User.UserName);

    }

    else

    {

       LblMessage.Text = User_Result.Errors.FirstOrDefault();

    }

}

Step 9: Add an App_Data folder to your project from Solution Explorer.

Add App_Data in Project

Step 9: Open the Web.config file and add the connection string in it as in the code shown below:

<connectionStrings>

     <add name="DefaultConnection" connectionString="Data Source=(LocalDb)\v11.0;AttachDbFilename=|DataDirectory|\IdentityApp.mdf;Integrated Security=True"

     providerName="System.Data.SqlClient" />

</connectionStrings>

Step 10: Make your Web Form as a Start Page and debug the application.

Register New User  Successful Registration

Working with LocalDB

As you saw, the user registered successfully. Create more users. Use the following procedure to verify that the users are registered by the Entity Framework in the Local Database.

Step 1: Open the Server Explorer from View.

Server Explorer in View

Step 2: Now you can show your table in the DefaultConnection as shown below:

Table in Server Explorer

Table Data in Server Explorer

Configure the OWIN Authentication

So far we have added support to register the new user. We now add support of user login to the application. The ASP.NET Identity uses OWIN Authentication as a default for forms authentication. The OWIN Cookie Authentication is a cookie and claims based authentication packages can be used by any framework that is hosted on OWIN or IIS.

Install the OWIN Authentication

Step 1: In Solution Explorer, right-click on the project to open the Manage NuGet Package and enter identity.owin in the search box and press Enter to install.

Owin Authentication in NuGet

Step 2: Enter the following statement and install the package:

Microsoft.Owin.Host.SystemWeb

Adding OWIN Startup Class

Step 3: Add the OWIN Startup class to your project from "Add new item" in Solution Explorer.

Owin Startup Class

Step 4: Replace the code with the following code.

Add the follow assemblies to your class:

using Microsoft.Owin.Security.Cookies;

using Microsoft.AspNet.Identity;

Now modify the code:

public void Configuration(IAppBuilder MyApp)

{

    MyApp.UseCookieAuthentication(new CookieAuthenticationOptions

    {

        AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,

        LoginPath = new PathString("/Login")

    });

}

Step 5: Open the Registration.cs page and modify the code with the following code.

Add the following assembly in your class:

using Microsoft.Owin.Security;

Add the highlighted code in the method as shown below:

void Register_User()

{

    var User_Store = new UserStore<IdentityUser>();

    var User_Manager = new UserManager<IdentityUser>(User_Store);

 

    var New_User = new IdentityUser() { UserName = TxtUserName.Text };

    IdentityResult User_Result = User_Manager.Create(New_User, TxtUserPassword.Text);

 

    if (User_Result.Succeeded)

    {

        var Auth_Manager = HttpContext.Current.GetOwinContext().Authentication;

        var User_Identity = User_Manager.CreateIdentity(New_User, DefaultAuthenticationTypes.ApplicationCookie);

        Auth_Manager.SignIn(new AuthenticationProperties() { }, User_Identity);

        Response.Redirect("~/Login.aspx");

    }

    else

    {

        LblMessage.Text = User_Result.Errors.FirstOrDefault();

    }

}

Step 6: Add a Web Form to your project named Login and add the code as shown below:

<form id="form1" runat="server">

   <div>

       <h3>Log In</h3>

       <hr />

 

       <asp:PlaceHolder runat="server" ID="LoginFormHolder" Visible="false">

           <div style="margin-bottom: 10px">

              <asp:Label runat="server" ID="LblUserName">User Name:</asp:Label>

              <div>

                  <asp:TextBox runat="server" ID="TxtUserName" />

              </div>

           </div>

           <div style="margin-bottom: 10px">

              <asp:Label runat="server" ID="LblUserPassword">Password</asp:Label>

              <div>

                  <asp:TextBox runat="server" ID="TxtUserPassword" TextMode="Password" />

              </div>

           </div>

           <div style="margin-bottom: 10px">

              <div>

                  <asp:Button runat="server" OnClick="SignIn_Click" Text="Log in" />

              </div>

           </div>

       </asp:PlaceHolder>

       <asp:PlaceHolder runat="server" ID="LogoutButtonHolder" Visible="false">

           <div>

              <div>

                  <asp:Button runat="server" OnClick="SignOut_Click" Text="Log out" />

              </div>

           </div>

       </asp:PlaceHolder>

           <asp:PlaceHolder runat="server" ID="LoginStatusHolder" Visible="false">

                <p>

                    <asp:Literal runat="server" ID="LtlStatus" />

                </p>

       </asp:PlaceHolder>

   </div>

</form>

Step 7: Open the Login.aspx.cs file and modify the code with the following code.

Add the following assemblies:

using Microsoft.AspNet.Identity;

using Microsoft.AspNet.Identity.EntityFramework;

using Microsoft.Owin.Security;

Code:

protected void Page_Load(object sender, EventArgs e)

{

    if (!IsPostBack)

    {

        if (User.Identity.IsAuthenticated)

        {

           LtlStatus.Text = string.Format("Hello {0}!!", User.Identity.GetUserName());

           LoginStatusHolder.Visible = true;

           LogoutButtonHolder.Visible = true;

        }

        else

        {

           LoginFormHolder.Visible = true;

        }

    }

}

 

protected void SignIn_Click(object sender, EventArgs e)

{

    var User_Store = new UserStore<IdentityUser>();

    var User_Manager = new UserManager<IdentityUser>(User_Store);

    var User = User_Manager.Find(TxtUserName.Text, TxtUserPassword.Text);

 

    if (User != null)

    {

        var Auth_Manager = HttpContext.Current.GetOwinContext().Authentication;

        var User_Identity = User_Manager.CreateIdentity(User, DefaultAuthenticationTypes.ApplicationCookie);

 

        Auth_Manager.SignIn(new AuthenticationProperties() { IsPersistent = false }, User_Identity);

        Response.Redirect("~/Login.aspx");

    }

    else

    {

        LtlStatus.Text = "Invalid username or password.";

        LoginStatusHolder.Visible = true;

    }

}

 

protected void SignOut_Click(object sender, EventArgs e)

{

    var Auth_Manager = HttpContext.Current.GetOwinContext().Authentication;

    Auth_Manager.SignOut();

    Response.Redirect("~/Login.aspx");

}

Step 8: Ctrl+F5 to run the application.

Registering User LogOut Page

Step 9: After logout, if you enter the invalid credentials then the following error message will displayed:

Login Page

Summary

With this article you have learned how ASP.NET Identity in the Empty Project Template works. You can also apply the OWIN Cookie Authentication to your application to apply the Forms Authentication in your project. Thanks for reading. Happy Coding.

X

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

Start Learning Now