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

Customize User Profile Info in MVC With ASP.NET Identity

Posted By: Ajay Saptaputre, 04 Jan,2016  |  Total View : 9738

In my previous article, I discussed about How to extend the properties of Identity with additional custom properties in ASP.NET , ASP.NET Identity Authentication - User Login and Registration Form and Understanding ASP.NET Identity .

In this article, I am going to explain how to customize User's Profile and add some more fields like FirstName, LastName, EmailID, DOB etc with ASP.NET Identity System. ASP.NET Identity allow you to add login features to our application and makes it easy like never before to customize data about the logged in user. I this article, I will discuss about what is OWIN, how to setup start-up class etc.

Create New Project

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:


Installing OWIN

Step 1: 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.Owin - This namespace has number of classes that support OWIN collection. The class provides a set of helper types and abstractions for simplifying the creation of OWIN Components.
  • Microsoft.owin.host.systemweb - This namespace contains the types to handling OWIN requests.
  • Microsoft.aspnet.identity.owin - This package contains functionality that which provides OWIN authentication in ASP.NET applications. This is very important functionality for login and call into OWIN Cookie Authentication to generate a cookie.
  • Microsoft.owin.security.cookies - This namespace is used to add a cookie based authentication to the application.
  • Microsoft.owin.security.oauth - This namespace enables an application to support any standard OAuth 2.0 authentication workflow.

OWIN Statup and Configuration

Step 1: Now, right click on project and add 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.

Open the StartUp class, you will find Configuration method which accepts parameter of type IAppBuilder. This Parameter is supplied by the Host at the run time. Add below code in StartUp class file.



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

Instance Per Request

Step 1: Instance per request means, only single instance for each request will be created and handled by the application. In this sample code I am using app.CreatePerOwinContext<T>() generic method to create single instance of given type per request. The created instance is stored in OwinContest for further use. Add below code inside the Configuration method.


app.CreatePerOwinContext(ApplicationDbContext.Create);
app.CreatePerOwinContext(IdentityUserManager.Create);

Add Create Method In IdentityUserStore and ApplicationDbContext Class

Step 1: Now, add new class file in Models folder and name as LoginUser.cs. You can observe that LoginUser class is implementing IdentityUser interface. The LoginUser class including customize properties which reflects in the database schema and Entity Framework will generate when the application first runs. You need to add static create method in the ApplicationDbContext class.


public class LoginUser : IdentityUser
{
	public string FirstName { get; set; }
	public string LastName { get; set; }
	public string EmailID { get; set; }
	public DateTime DOB { get; set; }
}
public class ApplicationDbContext : IdentityDbContext
{
	public ApplicationDbContext()
		: base("DefaultConnection")
	{
	}
	public static ApplicationDbContext Create()
	{
		return new ApplicationDbContext();
	}
}

Adding Custom Fields In RegisterViewModel

Step 1: Now, right click on "Models" folder and add new class name as "RegisterViewModel.cs". Now add customized user profile properties that you want to capture in registration page and insert into database.


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

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

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

[Required]
[Display(Name = "DOB")]
[DataType(DataType.Date)]
public DateTime DOB { get; set; }

Managing Users

Step 1: Now, right click on App_Start folder and add new class name as IdentityConfig.cs. Add two classes IdentityUserStore and IdentityUserManager.The IdentityUserStore class implementing 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 implementing UserManager class which is Entity Framework's that including methods for managing users.


public class IdentityUserStore : UserStore
{
	public IdentityUserStore(ApplicationDbContext context)
		: base(context) {      }
}
public class IdentityUserManager : UserManager
{
	public IdentityUserManager(IUserStore store)
		: base(store)  {      }

	public static IdentityUserManager 
	Create(IdentityFactoryOptions options, IOwinContext context)
	{
		var manager = 
		new IdentityUserManager(new UserStore(context.Get()));
		return manager;
	}
}

Adding AccountController

Step 1: Now, right click on Controllers folder and add new controller name as AccountController.cs. In order to receive posted user data, add Login and Register methods. An instance of a IdentityUserManager is created and called Create method to create new user.


[HttpPost]
public ActionResult Login(LoginViewModel loginModel)
{
IdentityUserStore Store = new IdentityUserStore(new ApplicationDbContext());
IdentityUserManager 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)
{
string result = string.Empty;
IdentityUserStore Store = new IdentityUserStore(new ApplicationDbContext());
IdentityUserManager userManager = new IdentityUserManager(Store);

var user = new LoginUser() { UserName = registerModel.UserName, 
FirstName = registerModel.FirstName, EmailID = registerModel.EmailID, 
LastName = registerModel.LastName, 
DOB = registerModel.DOB };
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();
}

Adding a Registration and Login Form

Now, create a new Razor Web Pages called Register.cshtml and Login.cshtml

Adding Connection String

In this sample code, I am using below connection string in web.config file. You can change as per your requirement.


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

Run Application

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.



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 ⇩