Getting started with ASP.NET IDENTITY

Rama Sagar
Posted by in ASP.NET category on for Beginner level | Points: 250 | Views : 7138 red flag
Rating: 5 out of 5  
 1 vote(s)

ASP.NET Identity is the new membership system for building ASP.NET web applications. ASP.NET Identity allows you to add login features to your application and makes it easy to customize data about the logged in user.

Introduction


This article explains us to how to add ASP.NET Identity to our ASP.NET Applications.ASP.NET Identity is a new membership system for ASP.NET.

It can be used with all of the ASP.NET frameworks such as ASP.NET MVC, Web Forms, Web Pages, Web API and Signal R

Objective


The objective of this article is to explain the steps of adding ASP.NET Identity to our ASP.NET Applications

Let’s get started with ASP.NET Identity

  • Step 1 Create a New Project Open visual studio 2013 -> click on File -> New Project -> Create new ASP.NET WebApplication -> Name it as Formsidentity.


  •    Step 2  Select Empty template and click on ok             





Notice the Change Authentication button is disabled and no authentication support is provided in this template. The Web Forms, MVC and Web API templates allow you to select the authentication approach. For more information, see Overview of Authentication


  • Step 3  Let’s add Identity Packages to our App 

                 Right click on Project-->Select Manage Nuget Packages




         



  After successful installation Let's add a simple Signup web form





  • Step 4  Add the below HTML to the form

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Signup.aspx.cs" Inherits="Formsidentity.Signup" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body style="font-family: Arial, Helvetica, sans-serif; font-size: small">
    <form id="form1" runat="server">
    <div>
        <h4 style="font-size: medium">Sign Up Form</h4>
        <hr />
        <p>
            <asp:Literal runat="server" ID="StatusMessage" />
        </p>                
        <div style="margin-bottom:10px">
            <asp:Label runat="server" AssociatedControlID="UserName">User name</asp:Label>
            <div>
                <asp:TextBox runat="server" ID="UserName" />                
            </div>
        </div>
        <div style="margin-bottom:10px">
            <asp:Label runat="server" AssociatedControlID="Password">Password</asp:Label>
            <div>
                <asp:TextBox runat="server" ID="Password" TextMode="Password" />                
            </div>
        </div>
        <div style="margin-bottom:10px">
            <asp:Label runat="server" AssociatedControlID="ConfirmPassword">Confirm password</asp:Label>
            <div>
                <asp:TextBox runat="server" ID="ConfirmPassword" TextMode="Password" />                
            </div>
        </div>
        <div>
            <div>
                <asp:Button runat="server" OnClick="CreateUser_Click" Text="Sign Up" />
            </div>
        </div>
    </div>
    </form>
</body>
</html>

Open the Signup.aspx.cs file and replace the contents of the file with the following code:


using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.EntityFramework;
using System;
using System.Linq;

namespace Formsidentity
{
    public partial class Signup : System.Web.UI.Page
    {
        protected void CreateUser_Click(object sender, EventArgs e)
        {
            // Default UserStore constructor uses the default connection string named: DefaultConnection
            //The UserStore class is the default EntityFramework implementation of a user store. This class implements the ASP.NET Identity Core’s minimal interfaces: IUserStore, IUserLoginStore, IUserClaimStore and IUserRoleStore.


            var userStore = new UserStore<IdentityUser>();


            //The UserManager class exposes user related APIs which will automatically save changes to the UserStore.


            var manager = new UserManager<IdentityUser>(userStore);

            //The IdentityUser class is the default EntityFramework implementation of the IUser interface. IUser interface is the minimal interface for a user on ASP.NET Identity Core.

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

            //The IdentityResult class represents the result of an identity operation.

            IdentityResult result = manager.Create(user, Password.Text);

            if (result.Succeeded)
            {
                StatusMessage.Text = string.Format("User {0} was created successfully!", user.UserName);
            }
            else
            {
                StatusMessage.Text = result.Errors.FirstOrDefault();
            }
        }
    }
}
  • Step 5  Now Lets add App_Data



  • Step 6  Open the Web.config file and add a connection string entry for the database which we will use to store user information. The database will be created at runtime by EntityFramework for the Identity entities. 
<?xml version="1.0" encoding="utf-8"?>
<!--
  For more information on how to configure your ASP.NET application, please visit
  http://go.microsoft.com/fwlink/?LinkId=169433
  -->
<configuration>
  <configSections>
    <!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
    <section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
  </configSections>
  <connectionStrings>
      <add name="DefaultConnection" connectionString="Data Source=(LocalDb)\v11.0;AttachDbFilename=|DataDirectory|\WebFormsIdentity.mdf;Initial Catalog=WebFormsIdentity;Integrated Security=True"
            providerName="System.Data.SqlClient" />
   </connectionStrings>
  <system.web>
    <compilation debug="true" targetFramework="4.5" />
    <httpRuntime targetFramework="4.5" />
  </system.web>
  <entityFramework>
    <defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
      <parameters>
        <parameter value="v11.0" />
      </parameters>
    </defaultConnectionFactory>
    <providers>
      <provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
    </providers>
  </entityFramework>
</configuration>

Debug the Application and we can have the following output 

        After Sign UP

 

Conclusion

In this article we have learned how to use ASP.NET Identity to a ASP.NET Application

Reference

http://www.asp.net/identity/overview/getting-started/introduction-to-aspnet-identity

Page copy protected against web site content infringement by Copyscape

About the Author

Rama Sagar
Full Name: RamaSagar Pulidindi
Member Level: Silver
Member Status: Member,MVP
Member Since: 12/30/2012 1:51:40 AM
Country: India
ramasagar
http://www.ramasagar.com
A Software Profesional working in Microsoft .NET technologies since year 2008, and I work for Dake ACE. I am passionate about .NET technology and love to contribute to the .NET community at Dot Net Funda

Login to vote for this post.

Comments or Responses

Posted by: Sheonarayan on: 11/22/2013 | Points: 25
Very good article Rama Sagar.

Well presented.

Thanks
Posted by: Rama Sagar on: 11/22/2013 | Points: 25
@Sheonarayan Thank you sir.......

Login to post response

Comment using Facebook(Author doesn't get notification)