Web Tutorials

HTML Tutorial
HTML5 Tutorial
Bootstrap3 Tutorial
Javascript Tutorial
TypeScript Tutorial
AngularJS Tutorial
CSharp Tutorial
.NET Tutorial
PHP Tutorial

Interview Q & A

ASP.NET Q & A
WEB API Q & A
WCF Q & A
JQuery Q & A
MVC Q & A
Bootstrap Q & A
LINQ Q & A
AJAX Q & A
SQL Server Q & A
C# Q & A
OOPS Q & A

Code Examples

AngularJS
Google MAP API V3
ASP.NET

Utility Tools

Html Encode
Html Decode
URL Decode
URL Encode
Base64 Encode
Base64 Decode
JSON Beautifier

ASP.NET Identity Authentication - User Login and Registration Form

Posted By: Ajay Saptaputre, 02 Jan,2016  |  Total View : 20070

In my previous article I discussed about Understanding ASP.NET Identity , ASP.NET Identity Vs Membership System and Features of ASP.NET Identity .

In this article, I am going to explain how to implement ASP.NET Identity using OWIN middleware components for authentication, including support for log-ins using external identity providers (like Microsoft Accounts, Facebook, Google, Twitter), and log-ins using organizational accounts from on-premises Active Directory. OWIN also support for OAuth.

ASP.NET Identity is new approach to implement membership in ASP.NET application and now part of new ASP.NET MVC 5 and web form project. ASP.NET Identity targets version 4.5 of the .NET Framework. That means, when you create MVC 5 application Identity will be automatically added into your project. In this article, I am going to demonstrate the necessary steps required to implement ASP.NET Identity framework in MVC 5 Web Pages application. To know more about ASP.NET Identity, read my previous article "Understanding ASP.NET Identity"

Start Creating New ASP.NET MVC 5 Empty Project

The first step in this walk through involves creating new MVC empty project. So let's open Visual Studio and start creating new MVC 5 project. In this article, I am using Visual Studio Express 2013 for Web but you can use Visual Studio 2013 as well. So start creating ASP.NET MVC 5 project in Visual Studio 2013.

By default, ASP.NET Identity uses SQL Server database. But you have greater flexibility to change with other database such as Oracle, MySQL, SharePoint, NoSql and any other database as well.

Step 1: Start Visual studio 2013, click on New Project from File menu and select Web and then ASP.NET web application from New Project. I am selecting .Net framework 4.5 to build this sample application. Now give proper name as ASPNETMVCIdentity to your application and click Ok button. Select Empty and checked MVC then click on "Ok" button as bellow screen shot illustrate:


Step 2: Now, you will need to add below listed packages that will help you to implement ASP.NET Identity in your application. All right, right click on project or go to Tool menu and select Library Package Manager and then select Manage NuGet Package for Solution... option.



Microsoft.AspNet.Identity.EntityFramework
Microsoft.AspNet.Identity.Core
Microsoft.Owin.Host.SystemWeb
Microsoft.Owin.Security.Cookies
Microsoft.AspNet.Web.Optimization

Step 3: Now, add new class file in Models folder and name as IdentityModels.cs. You can observe that LoginUser class is implementing IdentityUser interface. The LoginUser class includes other properties which are reflected in the database schema that Entity Framework will generate when the application first runs. In order to use Entity Framework code first, you will need to create "DbContext" class that derives from "IdentityDbContext" class by passing LoginUser class. Add below code in newly added class file.


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Microsoft.AspNet.Identity.EntityFramework;
using Microsoft.AspNet.Identity;

namespace MVCIdentity.Models
{
    public class LoginUser : IdentityUser
    {
        
    }
    public class LoginUserDbContext : IdentityDbContext
    {
        public LoginUserDbContext()
            : base("DefaultConnection")
        {
        }
    }
}

Adding RegisterViewModel

Step 1: Now, right click on Models folder and add new class name as RegisterViewModel.cs. Now add user profile properties that you want to capture in registration page. Also add required validation as per your requirement. Remember, you need to add System.ComponentModel.DataAnnotations namespace which is required to add validation in model.


using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;

namespace MVCIdentity.Models
{
public class RegisterViewModel
{
	[Required]
	[Display(Name = "User name")]
	public string UserName { get; set; }

	[Required]
	[StringLength(100, ErrorMessage = 
	"The {0} must be at least {2} characters long.", MinimumLength = 6)]
	[DataType(DataType.Password)]
	[Display(Name = "Password")]
	public string Password { get; set; }

	[DataType(DataType.Password)]
	[Display(Name = "Confirm password")]
	[Compare("Password", ErrorMessage = 
	"The password and confirmation password do not match.")]
	public string ConfirmPassword { get; set; }

	[Required]
	[Display(Name = "Email")]
	public string Email { get; set; }

	[Required]
	[Display(Name = "Phone")]
	public string PhoneNumber { get; set; }
}
}

Adding LoginViewModel

Step 1: Now, right click on Models folder and add new class name as LoginViewModel.cs. Now add user LOGIN properties that you want to use in login page. Also add required validation as per your requirement. Remember, you need to add System.ComponentModel.DataAnnotations namespace which is required to add validation in model.


using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;

namespace MVCIdentity.Models
{
    public class LoginViewModel
    {
        [Required]
        [Display(Name = "User name")]
        public string UserName { get; set; }

        [Required]
        [DataType(DataType.Password)]
        [Display(Name = "Password")]
        public string Password { get; set; }
    }
}

Adding IdentityConfig

Step 1: Now, right click on App_Start folder and add new class name as IdentityConfig.cs. Add two classes IdentityUserStore and IdentityUserManagerThe IdentityUserStore class implanting UserStore class which is an Entity Framework specific class that provides data access methods for communicating with the underlying SQL Server database. On the other hand, The IdentityUserManager class implemting UserManager class which is Entity Framework's that including methods for managing users.


using Microsoft.AspNet.Identity;
using MVCIdentity.Models;
using Microsoft.Owin;
using Microsoft.Owin.Security;
using Microsoft.AspNet.Identity.Owin;

namespace MVCIdentity.AppStart
{
    public class IdentityUserStore : UserStore
    {
        public IdentityUserStore(LoginUserDbContext context)
            : base(context) {      }
    }

    public class IdentityUserManager : UserManager
    {
        public IdentityUserManager(IUserStore store)
            : base(store)  {      }
    }
}

Adding Home Controller

Step 1: Now, right click on Controllers folder and add new controller name as HomeController.cs. In order to receive posted user data, you will need to add methods in HomeController class. An instance of a UserManager is created in the code. The UserManager.Create method is called to create new user which return type of this method is an instance of the IdentityResult class. It has a Succeeded property which is a bool, and indicates that whether operation was successful or not. Replace below code in HomeController.cs class.


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MVCIdentity.Models;
using Microsoft.AspNet.Identity.EntityFramework;
using Microsoft.AspNet.Identity;
using MVCIdentity.AppStart;
using Microsoft.Owin.Security;

namespace MVCIdentity.Controllers
{
public class HomeController : Controller
{
	
public ActionResult Login()
{
	return View();
}
public ActionResult Register()
{
	return View();
}

[HttpPost]
public ActionResult Login(LoginViewModel loginModel)
{
	var store = new IdentityUserStore(new LoginUserDbContext());
	var userManager = new IdentityUserManager(store);
	var user = userManager.Find(loginModel.UserName, loginModel.Password);
	if (user != null)
	{
		var authenticationManager = Request.GetOwinContext().Authentication;
		var userIdentity = userManager.CreateIdentity(user, 
		DefaultAuthenticationTypes.ApplicationCookie);

		authenticationManager.SignIn(new AuthenticationProperties() { }, userIdentity);
		ViewBag.Message = string.Format("User {0} Login Successfully", user.UserName);
		return View();

	}
	else
	{
		ViewBag.Message = "Invalid login or password";
	}
	return View();
}

[HttpPost]
public ActionResult Register(RegisterViewModel registerModel)
{

	var store = new IdentityUserStore(new LoginUserDbContext());
	var userManager = new IdentityUserManager(store);

	string result = string.Empty;
	var user = new LoginUser() { UserName = registerModel.UserName, 
	Email = registerModel.Email, PhoneNumber = registerModel.PhoneNumber };
	IdentityResult identityResult = userManager.Create(user, registerModel.Password);
	if (identityResult.Succeeded)
	{
		ViewBag.Message = string.Format("User {0} Successfully Created", user.UserName);
		var authenticationManager = Request.GetOwinContext().Authentication;
		var userIdentity = userManager.CreateIdentity(user, 
		DefaultAuthenticationTypes.ApplicationCookie);
		authenticationManager.SignIn(new AuthenticationProperties() { }, userIdentity);
		return View("Login");
	}
	else
	{
		ViewBag.Message = identityResult.Errors.FirstOrDefault();
	}
	return View();
}
public ActionResult LogOut()
{
	var authenticationManager = Request.GetOwinContext().Authentication;
	authenticationManager.SignOut();
	ViewBag.Message = "Logout Successfully";
	return View("Login");
}
}
}

Adding a Registration Form

Step 1: Now, create a new Razor Web Page called Register.cshtml and replace the existing code with the following:


@model MVCIdentity.Models.RegisterViewModel
@{
    ViewBag.Title = "Register";
}

<h2>@ViewBag.Message</h2>

@using (Html.BeginForm("Register", "Home", FormMethod.Post, new { @class = "form-horizontal", role = "form" }))
{
    @Html.AntiForgeryToken()
    <h4>Create a new account.</h4>
    <hr />
    @Html.ValidationSummary()
    <div class="form-group">
        @Html.LabelFor(m => m.UserName, new { @class = "col-md-2 control-label" })
        <div class="col-md-10">
            @Html.TextBoxFor(m => m.UserName, new { @class = "form-control" })
        </div>
    </div>
    <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" })
        </div>
    </div>
    <div class="form-group">
        @Html.LabelFor(m => m.PhoneNumber, new { @class = "col-md-2 control-label" })
        <div class="col-md-10">
            @Html.TextBoxFor(m => m.PhoneNumber, new { @class = "form-control" })
        </div>
    </div>
    <div class="form-group">
        @Html.LabelFor(m => m.Password, new { @class = "col-md-2 control-label" })
        <div class="col-md-10">
            @Html.PasswordFor(m => m.Password, new { @class = "form-control" })
        </div>
    </div>
    <div class="form-group">
        @Html.LabelFor(m => m.ConfirmPassword, new { @class = "col-md-2 control-label" })
        <div class="col-md-10">
            @Html.PasswordFor(m => m.ConfirmPassword, new { @class = "form-control" })
        </div>
    </div>
    <div class="form-group">
        <div class="col-md-offset-2 col-md-10">
            <input type="submit" class="btn btn-default" value="Register" />
        </div>
    </div>
    <p>
    @Html.ActionLink("Login", "Login") if you have a local account.
</p>
}

Adding a Login Form

Step 1: Now, create a new Razor Web Page called Login.cshtml and replace the existing code with the following:


@model MVCIdentity.Models.LoginViewModel

@{
    ViewBag.Title = "Log in";
}

<h2>Login User</h2>
<div class="row">
    <div class="col-md-8">
<section id="loginForm">

	@using (Html.BeginForm("Login", "Home", 
	new { ReturnUrl = ViewBag.ReturnUrl }, FormMethod.Post, 
	new { @class = "form-horizontal", role = "form" }))
	{
	@Html.AntiForgeryToken()
	<h4>@ViewBag.Message</h4>
		<hr />
	@Html.ValidationSummary(true)
	<div class="form-group">
		@Html.LabelFor(m => m.UserName, new { @class = "col-md-2 control-label" })
		<div class="col-md-10">
			@Html.TextBoxFor(m => m.UserName, new { @class = "form-control" })
			@Html.ValidationMessageFor(m => m.UserName)
		</div>
	</div>
	<div class="form-group">
		@Html.LabelFor(m => m.Password, new { @class = "col-md-2 control-label" })
		<div class="col-md-10">
			@Html.PasswordFor(m => m.Password, new { @class = "form-control" })
			@Html.ValidationMessageFor(m => m.Password)
		</div>
	</div>

	<div class="form-group">
		<div class="col-md-offset-2 col-md-10">
			<input type="submit" value="Log in" class="btn btn-default" />
		</div>
	</div>
	<p>
	@Html.ActionLink("Register", "Register") if you don't have a local account.
	</p>
	<p>
	@Html.ActionLink("LogOut", "LogOut") if you want to login with other local account.
	</p>
	}
</section>
</div>
</div>

Authenticating Users

Step 1: Now, add new class file Owin StartUp class in your project and name as StartUp.cs. In the MVC 5 templates, the StartUp class is used to wire up the authentication middleware which is all built on top of OWIN. The StartUp class is basically convention for Katana/OWIN to initialize the pipeline. When you run your application, the code inside of the StartUp class will run to set up the components that will be used. Add below code in newly added class file.



using System;
using System.Threading.Tasks;
using Microsoft.Owin;
using Owin;
using Microsoft.Owin.Security.Cookies;
using Microsoft.AspNet.Identity;

[assembly: OwinStartup(typeof(MVCIdentity.Startup))]

namespace MVCIdentity
{
    public class Startup
    {
        public void Configuration(IAppBuilder app)
        {
            app.UseCookieAuthentication(new CookieAuthenticationOptions
            {
                AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
                LoginPath = new PathString("/Login.cshtml")
            });
        }
    }
}

Adding Connection String


<connectionStrings> 
 <add name="DefaultConnection" providerName="System.Data.SqlClient" 
 connectionString="Server=LocalHost;Database=IdentityDataBase;
 Integrated Security=True;" /> 
</connectionStrings>

Run Application

Step 1: All right, now your application is ready to run. Enter required fields in registration page and click on Register button. After successful registration you will redirected to login page with registered user name and SignOut link i.e. "Jimi" in example code.



Appreciate your valuable feedback:

I hope this article is useful for you. I look forward for your comments and feedback. So please provide your valuable feedback so that I can make this blog better. You can also share this article by hitting below button.
Happy learning...

Download Code ⇩