简体   繁体   中英

Lazy Loading issue while overriding UserClaimsPrincipalFactory in IdentityServer4

I have an empty claim while trying to add the ApplicationUser property as a claim in identity. Looks like ef have an issue with the lazy loading of the two following properties.

public class ApplicationUser : IdentityUser
{
    public virtual ApplicationUser Manager { get; set; }
    public virtual List<ApplicationUser> ManagerOf { get; set; }
}

I know that I'm entering in this piece of code. But inside GenerateClaimsAsync, The user has its property set to null ( only the two above ). And I checked in Database, I have the values well defined.

public class MyUserClaimsPrincipalFactory : UserClaimsPrincipalFactory<ApplicationUser>
{
    public MyUserClaimsPrincipalFactory(
        UserManager<ApplicationUser> userManager,
        IOptions<IdentityOptions> optionsAccessor)
        : base(userManager, optionsAccessor)
    {
    }

    protected override async Task<ClaimsIdentity> GenerateClaimsAsync(ApplicationUser user)
    {
        var identity = await base.GenerateClaimsAsync(user);
        var managerId = "";
        if (user.Manager?.Id != null)
        {
            managerId = user.Manager.Id;
        }
        identity.AddClaim(new Claim("manager_id", managerId));
        var managerOf = "";
        if (user.ManagerOf != null)
        {
            managerOf = string.Join(", ", user.ManagerOf.Select(u => u.Id).ToArray());     
        }

        identity.AddClaim(new Claim("manager_of", managerOf));
        return identity;
    }
}

Do you guys have an idea ?

Thank you !

As @mackie pointed out, lazy loading is not enabled by default. I only needed to enable the lazy loading by following this tutorial: https://www.learnentityframeworkcore.com/lazy-loading .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM