However, this has the drawback of calling the database with each HTTP request. So instead of calling the database with every http request, I simply wanted to do so once (during initial authentication).
You can do so by using the IUserClaimsPrincipalFactory.
For example, how to add the Phone number to ClaimsIdentity is described below.
(1) Add the following class as the service:
using Microsoft.AspNetCore.Identity;
using Microsoft.Extensions.Options;
using MvcCore6App2.Data;
using System.Security.Claims;
namespace MvcCore6App2.Services
{
public class CustomClaimsPrincipalFactory :
UserClaimsPrincipalFactory<ApplicationUser>
{
public CustomClaimsPrincipalFactory(
UserManager<ApplicationUser> userManager,
IOptions<IdentityOptions> optionsAccessor)
: base(userManager, optionsAccessor)
{
}
// This method is called only when login. It means that "the drawback
// of calling the database with each HTTP request" never happen.
public async override Task<ClaimsPrincipal> CreateAsync(ApplicationUser user)
{
var principal = await base.CreateAsync(user);
if (!string.IsNullOrEmpty(user.PhoneNumber))
{
if (principal.Identity != null)
{
((ClaimsIdentity)principal.Identity).AddClaims(
new[] { new Claim("Phone", user.PhoneNumber) });
}
}
return principal;
}
}
}
(2) Register the above service in the Program.cs as follows:
builder.Services.AddScoped<IUserClaimsPrincipalFactory<ApplicationUser>,
CustomClaimsPrincipalFactory>();
(3) Result after login: