Customizing profile information in ASP.NET Identity in VS 2013 templates

Customizing profile information in ASP.NET Identity in VS 2013 templates

Rate This
  • Comments 41

ASP.NET Identity is the new membership system for ASP.NET applications. To learn more about ASP.NET Identity please visit http://blogs.msdn.com/b/webdev/archive/2013/06/27/introducing-asp-net-identity-membership-system-for-asp-net-applications.aspx

One of the mainline features about ASP.NET Identity is to make it easy to add profile information about the user. In the existing ASP.NET Membership system, User and Profile were separate tables and Profile information about the user was retrieved by using the Profile provider. This made it difficult to customize the Profile information and associate it with the User and application data.  ASP.NET Identity makes it really easy to add profile data for your User.

[Update] Adding information on how to store profile information in a different table

[Update] Rick Anderson has a tutorial on asp.net site which also shows how you can add Social Logins to the template as well. Please refer to the tutorial for an entire walkthrough

http://www.asp.net/mvc/tutorials/mvc-5/create-an-aspnet-mvc-5-app-with-facebook-and-google-oauth2-and-openid-sign-on


This post shows how you can customize profile information about the user when you start with the project templates in Visual Studio 2013. Following are the steps to follow to add profile information about the user.

    • In Visual Studio 2013, create a new ASP.NET MVC application.
      • You can create a Web Forms application and follow the same steps to add profile information.
    • Run the application and register a user
      • You would notice that at the registration screen, the application only asks for a UserName and password. Let’s say that you wanted to add one more field called BirthDate that the users should specify when registering a user.
    • Enable Entity Framework Migrations
      • Migrations are recommended to use when you are modifying the schema of the database or you are changing the Code First Model. ASP.NET Identity uses Entity Framework Code First as an underlying framework. For more information on EF migrations please visit http://msdn.microsoft.com/en-us/data/jj591621
      • Open Package Manager Console by doing Tools – Library Package Manager – Package Manager Console
      • image
      • Type in “Enable-Migrations” and press enter
    • Add properties for the Profile information that you want to store.
      • In our example we will add BirthDate as a property
      • Goto Models\IdentityModels.cs and add the following property to ApplicationUser
public class ApplicationUser : IdentityUser { public DateTime BirthDate { get; set; } }
      • Add using System; at the top of the class.
    • Add-Migrations to modify the database
      • Since we have added a new property to the User, we need to update the database to reflect this change. This is where EF migrations is really useful. You can use migrations to update the database schema by doing the following
      • Goto Package Manager console and do the following
      • Add-Migration "Birthdate"
        • This will add a migration file to your project
      • Update-Database
        • This command will run all the migration files and update the database schema to add a BirthDate column
    • Modify the application to add a BirthDate field
      • The steps here are specific to how you would add a view to MVC, but you can do similar view specific rendering in Web Forms as well
      • Add BirthDate to RegisterViewModel in Models\AccountViewModels.cs
   1:  public class RegisterViewModel { 
   2:  [Required] [Display(Name = "User name")] 
   3:  public string UserName { get; set; }  
   4:   
   5:  [Required] 
   6:  [StringLength(100, ErrorMessage = "The {0} must be 
       at least {2} characters long.", MinimumLength = 6)] 
   7:  [DataType(DataType.Password)] [Display(Name = "Password")] 
   8:  public string Password { get; set; }  [DataType(DataType.Password)]
        [Display(Name = "Confirm password")] 
   9:   
  10:  [Compare("Password", ErrorMessage = 
       "The password and confirmation password do not match.")] 

11: public string ConfirmPassword { get; set; }

public DateTime BirthDate { get; set; } }

        • Add using System; at the top of the class.
      • Update the Register view in Views\Account to add a field to enter BirthDate.
   1:  <div class="form-group">
   2:   @Html.LabelFor(m => m.BirthDate, new { @class = "col-md-2 control-label" }) 
   3:  <div class="col-md-10"> @Html.TextBoxFor(m => m.BirthDate, new { @class = "form-control" }) 
   4:  </div>
   5:   </div>
      • Update the Register Action in AccountController to store the BirthDate as well for the User
var user = new ApplicationUser() { UserName = model.UserName, BirthDate=model.BirthDate };
  • Run the application and register a user again. You will see the BirthDate field as shown below

 

    • image
  • Display the profile infromation on the page
    • When the User Logs in, you can display the profile information by doing the following
    • Get the current logged in UserId, so you can look the user up in ASP.NET Identity system
      • var currentUserId = User.Identity.GetUserId();
    • Instantiate the UserManager in ASP.Identity system so you can look up the user in the system
      • var manager = new UserManager<MyUser>(new UserStore<MyUser>(new MyDbContext()));
    • Get the User object
      • var currentUser = manager.FindById(User.Identity.GetUserId());
    • Get the profile information about the user
      • currentUser.BirthDate

Adding Profile information in a different table.

While this post shows you a way where you can easily add profile properties to the User Table itself. Since ASP.NET Identity uses Entity Framework, you can customize profile information as you would like to. For eg. let’s say that you want to add profile information in a different table rather than the same table then you can do the following to your model

Add a new class to store Profile information

Code Snippet
  1. public class MyUser : IdentityUser
  2.     {
  3.         public virtual MyUserInfo MyUserInfo { get; set; }
  4.     }
  5.  
  6.     public class MyUserInfo{
  7.         public int Id { get; set; }
  8.         public string FirstName { get; set; }
  9.         public string LastName { get; set; }
  10.     }
  11.     public class MyDbContext : IdentityDbContext<MyUser>
  12.     {
  13.         public MyDbContext()
  14.             : base("DefaultConnection")
  15.         {
  16.         }
  17.         public System.Data.Entity.DbSet<MyUserInfo> MyUserInfo { get; set; }
  18.      }

In this case when you run the application you will get the FirstName and LastName in a different table called MyUserInfo

image

Getting Profile information

  • When the User Logs in, you can display the profile information by doing the following
  • Get the current logged in UserId, so you can look the user up in ASP.NET Identity system
    • var currentUserId = User.Identity.GetUserId();
  • Instantiate the UserManager in ASP.Identity system so you can look up the user in the system
    • var manager = new UserManager<MyUser>(new UserStore<MyUser>(new MyDbContext()));
  • Get the User object
    • var currentUser = manager.FindById(User.Identity.GetUserId());
  • Get the profile information about the user
    • currentUser.MyUserInfo.FirstName

Conclusion

This post shows how you can customize the profile information about the user. If you have any questions, please leave comments or reach me at twitter (@rustd)

  • Hi. how can I retrieve and display that additional "Birthdate" property to a view? Thank you.

  • @Shibbir I update this post with a sample. Please check it out. You can also visit github.com/.../AspnetIdentitySample

  • Hi, how to change ID data type to Int ?

    Change to change table named "AspNetUsers" to User for this class ?

  • @Giang, since ASP.NET Identity uses the fluent APIs  in Entity Framework Code First, you can use the fluent APIs in onModelCreating event of your DbContext and change the tablenames. I have the following commit github.com/.../d8a0624797bdab75901206e62977a178bc9cb79a in my sample project that shows how to do this github.com/.../AspnetIdentitySample

    I am pasting the code here as well

    protected override void OnModelCreating(DbModelBuilder modelBuilder)

           {

               base.OnModelCreating(modelBuilder);

               modelBuilder.Entity<IdentityUser>()

                   .ToTable("Users");

               modelBuilder.Entity<MyUser>()

                   .ToTable("Users");

           }

  • Thanks a lot. One more question. How can I access User.Identity.GetUserId() from a class library project? What dll's are needed for that please.

  • User.Identity.GetUserId is an extension method on IIdentity. It is present in the Microsoft.AspNet.Identity.Core assembly

    Why do you need to access this in a class project? This extension method gives you the UserId and UserName from the ClaimsIdentity of the logged in user.

  • For example, I have a simple class Customer:

    public class Customer

    {

        public int Id { get; set; }

        public string Email { get; set; }

        /* This is the logged in user id. So that I can track which user created this customer */

        public string CreatedBy { get; set; }

    }

    I have a separate repository project that handles database operations (its a class library project). I could just pass the user id from controller to my repository project. But I wanted to grab the current user from my repository project.

    Thanks.

  • thanks for writing this up, but I have a question: I don't understand any part of the manager initialization:

    var manager = new UserManager<MyUser>(new UserStore<MyUser>(new MyDbContext()));

    what is the MyUser object I'm supposed to place in there, and am I also instantiating a new DbContext object? If so, does it work just declaring it like that and not referencing it elsewhere?

    thanks again

  • nevermind, I got it. Thanks again, sorry for the double-post

  • I'm loving the new ASP.NET Identity, but wondering given ASP.NET WebStack and Entity Framework are now open source is the ASP.NET Identity also open source?

  • ASP.NET Identity is not yet open sourced but it will be open sourced....

  • I'm getting this error when I try to add the Birthdate item:

    Mapping and metadata information could not be found for EntityType 'ArmyAviationLogbook.Models.ApplicationUser'.

    Line 91:                     Birthdate = model.Birthdate

    Line 92:                 };

    Line 93:                 var result = await IdentityManager.Users.CreateLocalUserAsync(user, model.Password);

    Line 94:                 if (result.Success)

    Line 95:                 {

    I have tried switching to inheriting IdentityUser instead of User but that class isn't recognized. How can I make this work?

  • I want to use email for username, but it rejects the submission with this error "User name xxx@yyy.com is invalid, can only contain letters or digits."

    how can change the restriction for username

    thanks

  • Hi ,

    I need to verify the user by emailing them an verification link like simplemembership.

    Is it possible with this, If not what are the options ?

    Thanks.

  • Good Day! Sir how can i add model and generate into database? Example i want to add Content Table and i code it to a class name Content.cs inside the folder model. When i run the program, it doesn't create the Table. please help me. Thanks

Page 1 of 3 (41 items) 123