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.
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 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.
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")
});
}
}
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);
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();
}
}
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; }
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
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;
}
}
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();
}
Now, create a new Razor Web Pages called Register.cshtml and Login.cshtml
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>
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.
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...