- Home
- ASP.NET Core
- Identity
- How to extend ASP.NET Core Identity user
How to extend ASP.NET Core Identity user
ASP.NET Core Identity has a default implementation that you can easily extend to fit your needs, like adding a first name and a last name to the users (we will not create new tables here).
-
1
First step to do that: implement the Identity user, and add the properties you need.
You also have to create the columns in your database, with the same names as the properties.// Add profile data for application users by adding properties to the ApplicationUser class public class ApplicationUser : IdentityUser { public string FirstName { get; set; } public string LastName { get; set; } } -
2
SignInManager
is a class responsible for signing users into your application. Internally, this class uses an IUserClaimsPrincipalFactory<TUser> to generate a ClaimsPrincipal from your user. To add claims to this factory (by default, IUserClaimsPrincipalFactory manages only two claims: the username and the user's identifier), you have to create your own implementation of IUserClaimsPrincipalFactory by inheriting from the default one: public class AppClaimsPrincipalFactory : UserClaimsPrincipalFactory<ApplicationUser, IdentityRole> { public AppClaimsPrincipalFactory( UserManager<ApplicationUser> userManager , RoleManager<IdentityRole> roleManager , IOptions<IdentityOptions> optionsAccessor) : base(userManager, roleManager, optionsAccessor) { } public async override Task<ClaimsPrincipal> CreateAsync(ApplicationUser user) { var principal = await base.CreateAsync(user); if (!string.IsNullOrWhiteSpace(user.FirstName)) { ((ClaimsIdentity)principal.Identity).AddClaims(new[] { new Claim(ClaimTypes.GivenName, user.FirstName) }); } if (!string.IsNullOrWhiteSpace(user.LastName)) { ((ClaimsIdentity)principal.Identity).AddClaims(new[] { new Claim(ClaimTypes.Surname, user.LastName), }); } return principal; } } -
3
Finally, you have to register the custom factory you just created in your application startup class, after adding the Identity service.
public void ConfigureServices(IServiceCollection services) { // [...] services.AddDbContext<SecurityDbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("Security"))); services.AddIdentity<ApplicationUser, IdentityRole>() .AddEntityFrameworkStores<SecurityDbContext>() .AddDefaultTokenProviders(); services.AddScoped<Microsoft.AspNetCore.Identity.IUserClaimsPrincipalFactory<ApplicationUser>, AppClaimsPrincipalFactory>(); // [...] }
30/10/2016

