ASP
Wednesday, 17 Jun 2020

How to customize or add data to Claim in ASP.NET Core

Sometimes we need to get some values from users' information when login. This caught information saves in Claim and we use them everywhere if we want. For example, we want to save the user's role, phone number, or ID. If we each time use the query and select those data from the database, we will impose additional overhead on the database. Thus, one of the best idea is that we use the Claim. In this video, I am going to show how to do it.

  1. Create a new project in ASP.NET MVC Core
  2. Create a .cs file called ClaimService.cs and copy below codes:
public class ClaimService : UserClaimsPrincipalFactory<IdentityUser, IdentityRole>
    {
        public ClaimService(
            UserManager<IdentityUser> userManager,
            RoleManager<IdentityRole> roleManager,
            IOptions<IdentityOptions> optionAccessor)
            : base(userManager, roleManager, optionAccessor)
        {

        }

        protected override async Task<ClaimsIdentity> GenerateClaimsAsync(IdentityUser user)
        {
            var claims = await base.GenerateClaimsAsync(user);
            claims.AddClaim(new Claim("ID", user.Id));
            claims.AddClaim(new Claim("PhoneNumber", user.PhoneNumber));
            claims.AddClaim(new Claim("UserName", user.UserName));

            //Add role to Claim
            //var UserRole = UserManager.GetRolesAsync(user);
            //claims.AddClaim(new Claim("Role", UserRole.Result.FirstOrDefault().ToString()));
            return claims;
        }

        public static Claim CreateClaim(string type, string value)
        {
            return new Claim(type, value, ClaimValueTypes.String);
        }
    }

}

 

  1. In Startup add :
services.AddDefaultIdentity<IdentityUser>(options => options.SignIn.RequireConfirmedAccount = true)
                .AddRoles<IdentityRole>()
                .AddEntityFrameworkStores<ApplicationDbContext>();

   services.AddTransient<IUserClaimsPrincipalFactory<IdentityUser>, ClaimService>();

If you want to which values have saved in Claim you can add below codes in a view.

@inject SignInManager<IdentityUser> SignInManager
@inject UserManager<IdentityUser> UserManager
@{
    foreach (var item in User.Claims)
    {
        <p>@item.Type : @item.Value</p>
    }
}

The result would be:

 

Recent Comments