Extending the ASP.NET Identity user
In the last few weeks, I wrote two blog posts: Using ASP.NET Identity and Using External Login in ASP.NET Identity. How I Added It to My MiniBlog Project" and "Part 2: Using External Login in ASP.NET Identity: How to Extend It with an External Login Provider." In this blog, I will explain how I extended the Identity user with custom fields to store additional profile information.
I extended the user with a display name so that I could show who commented on a post.
Create a class that inherits from IdentityUser
By default, IdentityDbContext works with the IdentityUser class to define the user table. To add custom properties, create your own class that inherits from IdentityUser. You can also add additional indexes if needed, for example:
[Index(nameof(DisplayName), IsUnique = true)]
public class ApplicationUser : IdentityUser
{
[MaxLength(64)]
public required string DisplayName { get; set; }
}
Update your DbContext
Update your DbContext. You need to configure it to use your custom user class for the Identity user table instead of the default one. For example, you can do this like this:
public class MiniBlogDbContext : IdentityDbContext<ApplicationUser> // specify your created user class here
{
// your own internal DbSet(s)
public MiniBlogDbContext(DbContextOptions<MiniBlogDbContext> options)
: base(options)
{
}
}
Replace IdentityUser with your custom class everywhere
Begin by updating Program.cs or Startup.cs where you register Identity. Replace IdentityUser with you custom user class.
// Replace the IdentityUser for you custom user class
builder.Services.AddIdentity<ApplicationUser, IdentityRole>(options => options.SignIn.RequireConfirmedAccount = true)
.AddRoles<IdentityRole>() // Only needed when you use roles in your application
.AddEntityFrameworkStores<DbContext>()
.AddDefaultTokenProviders();
The less fun part of it is that you also need to update all the scaffolded views that use IdentityUser and replace them with your custom user class. You also need to replace IdentityUser with your custom user class in any controller or other classes that use it. For example, in the login.cshtml.cs:
public LoginModel(SignInManager<ApplicationUser> signInManager, ILogger<LoginModel> logger)
{
_signInManager = signInManager;
_logger = logger;
}
Don’t Forget to Update the Database
After adding your custom user class and updating the DbContext, don’t forget to update your database schema.
dotnet ef migrations add AddCustomUserFields
dotnet ef database update
Wrapping Up
This was the final part of my series on adding ASP.NET Identity to my MiniBlog project. If something isn’t working as expected, I recommend starting from the beginning with Part 1: Using ASP.NET Identity to ensure everything is set up correctly.
Thanks for following along, I hope this series helped you integrate Identity into your own project.
Comments
Register or login to leave a comment