Adding claims in ASP.NET Identity membership

When using Identity middleware, adding claims is not as simple as with cookie middleware. We need to create a custom claims factory class that derives from the UserClaimsPrincipalFactory class and overrides the CreateAsync method that injects the user object. When the user is signed in, these claims will automatically be added in the cookie.

To create the claims factory class, add the following code:

    public class AppClaimsPrincipalFactory :
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,"Jason"),
new Claim(ClaimTypes.Surname,"Scott"),
new Claim(ClaimTypes.Role,"Manager"),
new Claim(ClaimTypes.Role, "Supervisor")
});
return principal;
}

In the preceding code snippet, we have overridden the CreateAsync method and added four claims, such as given name, surname, and two roles. When the user is signed in, the claims will be added in the cookie.

Finally, we have to inject the claims factory instance as a scoped object through Dependency Injection (DI) in the ConfigureServices method of the Startup class. This way, when the user is signing in, it will inject our custom claims factory class, AppClaimsPrincipalFactory, in the Identity system and use its CreateAsync method to add claims:

    services.AddScoped<IUserClaimsPrincipalFactory<ApplicationUser>,
AppClaimsPrincipalFactory>();
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.129.211.166