user16984156
user16984156

Reputation:

How can I extend the user table in identity in Blazor Server Side?

Is there any way to add additional fields in the User table in identity Blazor? because I have many user information such as firstname lastname and others and i want to bring all these when the user is logging in.

Upvotes: 0

Views: 914

Answers (1)

Zhi Lv
Zhi Lv

Reputation: 21381

To add custom user properties in ASP.NET Core Identity User table, you need to do the following steps:

  1. Create a Custom ApplicationUser class which inherits the IdentiyUser:

     public class ApplicationUser: IdentityUser
     {
         public int Age { get; set; }
         public string CustomTag { get; set; }
         public bool IsApproved { get; set; }
     }
    
  2. Update the ApplicationDbContext as below:

     public class ApplicationDbContext : IdentityDbContext
     {
         public DbSet<ApplicationUser> ApplicationUsers { get; set; }
         public DbSet<ApplicationRole> ApplicationRoles { get; set; } //custom Idnetity Role
         public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
             : base(options)
         {
         }
         protected override void OnModelCreating(ModelBuilder builder)
         {
             base.OnModelCreating(builder); 
         }
     }
    
  3. Update the Identity Configuration in the ConfigureServices method:

         services.AddIdentity<ApplicationUser, ApplicationRole>(options => options.SignIn.RequireConfirmedAccount = true)
                  .AddEntityFrameworkStores<ApplicationDbContext>()
                  .AddDefaultTokenProviders()
                  .AddDefaultUI();
    
  4. Enable migration and update the database with the following commands:

     Add-Migration CustomUserData
     Update-Database
    
  5. Check the database via SSMS.

    enter image description here

  6. Use Scaffold Identity generate the relate identity pages, such as: login, logout. Then, you can update the page content to base on the ApplicationUser model.

    [Note] In the Identity Page, they might still use the IdentityUser model, you need to change it to ApplicationUser.

More detail information, see the following tutorials:

Add, download, and delete custom user data to Identity in an ASP.NET Core project

How to add Custom User Properties in ASP.NET Core Identity

Upvotes: 2

Related Questions