Created
June 26, 2018 09:24
-
-
Save jmcd/f9b935ce47dcf22fc7b7d47a236a5c9d to your computer and use it in GitHub Desktop.
Adding dynamic claims to a principal
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class DynamicOrganizationRoleClaimsFactory : UserClaimsPrincipalFactory<ApplicationUser> | |
{ | |
private readonly ApplicationDbContext dbContext; | |
public DynamicOrganizationRoleClaimsFactory(UserManager<ApplicationUser> userManager, | |
IOptions<IdentityOptions> optionsAccessor, ApplicationDbContext dbContext) | |
: base(userManager, optionsAccessor) | |
{ | |
this.dbContext = dbContext; | |
} | |
public override async Task<ClaimsPrincipal> CreateAsync(ApplicationUser user) | |
{ | |
var principal = await base.CreateAsync(user); | |
var orgRoleClaims = dbContext.Set<OrganizationMembership>() | |
.Where(om => om.UserId == user.Id) | |
.Select(om => new Claim($"org_role_{om.Role}".ToLowerInvariant(), om.OrganizationId.ToString())); | |
((ClaimsIdentity) principal.Identity).AddClaims(orgRoleClaims); | |
return principal; | |
} | |
} | |
// at startup | |
services.AddScoped<IUserClaimsPrincipalFactory<ApplicationUser>, DynamicOrganizationRoleClaimsFactory>(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment