I create a React App using Visual Studio 2022 ASP.NET React Project Template. I was able to to modify the project to add some custom fields during registration. Those customer fields include First & Last Name.
I'd like to replace the email that is displayed on every page within the navigation menu:
I managed to successfully replace it on the Razor pages that are scaffolded in the Identity Framework.
But I can't seem to figure out how to do it on the React side of things. Any documentation you can point me is greatly appreciated.
CodePudding user response:
Go to ClientApp/src/components/api-authorization/LoginMenu.js
and change populateState
method to:
async populateState() {
const [isAuthenticated, user] = await Promise.all([authService.isAuthenticated(), authService.getUser()])
this.setState({
isAuthenticated,
userName: user && `${user.given_name} ${user.family_name}`
});
}
To map the FirstName
and LastName
properties to given_name
and family_name
claims you can use UserClaimsPrincipalFactory
:
public class AppUserClaimsPrincipalFactory : UserClaimsPrincipalFactory<ApplicationUser, IdentityRole>
{
public AppUserClaimsPrincipalFactory(
UserManager<ApplicationUser> userManager,
RoleManager<IdentityRole> roleManager,
IOptions<IdentityOptions> optionsAccessor)
: base(userManager, roleManager, optionsAccessor)
{
}
protected override async Task<ClaimsIdentity> GenerateClaimsAsync(ApplicationUser user)
{
var identity = await base.GenerateClaimsAsync(user);
identity.AddClaim(new Claim(JwtClaimTypes.GivenName, user.FirstName));
identity.AddClaim(new Claim(JwtClaimTypes.FamilyName, user.LastName));
identity.AddClaim(new Claim(JwtClaimTypes.BirthDate, user.DateOfBirth.ToString("yyyy-MM-dd"), ClaimValueTypes.Date));
return identity;
}
}
And in Startup.cs
add:
services.AddScoped<IUserClaimsPrincipalFactory<ApplicationUser>, AppUserClaimsPrincipalFactory>();
Assuming you have defined ApplicationUser
as:
public class ApplicationUser : IdentityUser
{
public string FirstName { get; set; }
public string LastName { get; set; }
public DateTime DateOfBirth { get; set; }
}