Custom claims information in .NET Core Identity on Microsoft .Net Development
The ASP.NET Core 2.0 default Claim implementation only includes username and user identifier claims. To add additional claims we can create our own implementation of IUserClaimsPrincipalFactory or derive from the default UserClaimsPrincipalFactory:
public class MyClaimsPrincipal : 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);
((ClaimsIdentity)principal.Identity).AddClaims(new[] {
new Claim(ClaimTypes.GivenName, user.FullName),
new Claim(ClaimTypes.DOB, user.DOB),
});
return principal;
}
}
Once create the custom Claim Principal then we need to register in startup.cs. To register the custom factory we add the following to the ConfigureServices method in startup.cs after the services.AddIdentity()
services.AddScoped<IUserClaimsPrincipalFactory<ApplicationUser>, MyClaimsPrincipal>();