I have two code snippets.
// Sample 1.
public class ApplicationUserClaimsPrincipalFactory : UserClaimsPrincipalFactory<ApplicationUser, IdentityRole> { public ApplicationUserClaimsPrincipalFactory(UserManager<ApplicationUser> userManager, RoleManager<IdentityRole> roleManager, IOptions<IdentityOptions> optionsAccessor) : base(userManager, roleManager, optionsAccessor) { } protected override async Task<ClaimsIdentity> GenerateClaimsAsync(ApplicationUser user) { // https://github.com/aspnet/Identity/blob/329eed9e8d14243d0b36385bb1adc9fc85df0e41/src/Core/UserClaimsPrincipalFactory.cs#L82 var identity = await base.GenerateClaimsAsync(user); // Todo... Add or replace identity.Claims. return identity; } }
// Sample 2.
public class ApplicationUserClaimsTransformation : IClaimsTransformation { private readonly UserManager<ApplicationUser> _userManager; public ApplicationUserClaimsTransformation(UserManager<ApplicationUser> userManager) { _userManager = userManager; } // Each time HttpContext.AuthenticateAsync() or HttpContext.SignInAsync(...) is called the claims transformer is invoked. So this might be invoked multiple times. public async Task<ClaimsPrincipal> TransformAsync(ClaimsPrincipal principal) { var identity = principal.Identities.FirstOrDefault(x => x.IsAuthenticated); if (identity == null) return principal; var user = await _userManager.GetUserAsync(principal); if (user == null) return principal; // Todo... Add or replace identity.Claims. return new ClaimsPrincipal(identity); } }
I am not clear which sample should be used when manipulate claims at "// Todo... Add or replace identity.Claims.". Thanks.