我的自定义添加的声明有时在两个请求之间不存在

时间:2019-06-20 19:25:25

标签: asp.net-core asp.net-identity asp.net-core-identity

我正在尝试覆盖asp.net核心标识中的声明生成。有时,即使我在UserClaimsPrincipalFactory中添加了我的自定义,它也会产生明确的声明

public class ClaimsPrincipalFactory: UserClaimsPrincipalFactory<ApplicationUser, ApplicationRole>
{
    private readonly IUserReader _userReader;
    private readonly IRolesClaimPrincipalHelper _roleClaimsPrincipal;

    public ClaimsPrincipalFactory(
        UserManager<ApplicationUser> userManager,
        RoleManager<ApplicationRole> roleManager,
        IOptions<IdentityOptions> optionsAccessor,
        IUserReader userReader,
        IRolesClaimPrincipalHelper claimPrincipalHelper)
    : base(userManager, roleManager, optionsAccessor)
    {
        _userReader = userReader;
        _roleClaimsPrincipal = claimPrincipalHelper;
    }

    public async override Task<ClaimsPrincipal> CreateAsync(ApplicationUser user)
    {
        var id = await GenerateClaimsAsync(user);

        return new ClaimsPrincipal(id);
    }

    protected override async Task<ClaimsIdentity> GenerateClaimsAsync(ApplicationUser user)
    {
        var id = await base.GenerateClaimsAsync(user);

        var userWithRoles = _userReader.FindByEmail(user.Email);
        var rolesPerSubscription = _userReader.GetRolesPerSubscription(userWithRoles);
        var rolesPerSubscriptionClaims = _roleClaimsPrincipal.GetClaims(rolesPerSubscription);

        if (rolesPerSubscriptionClaims.Any())
        {
            id.AddClaims(rolesPerSubscriptionClaims);

            if (rolesPerSubscription.Any(x => x.Roles.Contains(RoleHelper.MobileWorker)))
            {
                id.AddClaim(new Claim(Options.ClaimsIdentity.RoleClaimType, RoleHelper.MobileWorker));
            }
        }

        return id;
    }
}

因此需要为每个请求生成声明

    if (rolesPerSubscriptionClaims.Any())
            {
                id.AddClaims(rolesPerSubscriptionClaims);

                if (rolesPerSubscription.Any(x => x.Roles.Contains(RoleHelper.MobileWorker)))
                {
                    id.AddClaim(new Claim(Options.ClaimsIdentity.RoleClaimType, RoleHelper.MobileWorker));
                }
            }

但是有时不会生成其他声明,因此可以使用默认声明,但是缺少我的自定义设置。我检查了所有要求是否都满足生成我的自定义声明和要求的所有要求。所以我真的不明白它是如何有选择地跳过我的自定义声明的。 我根据教程注册了Claims工厂,主要要点是在某些请求中我的自定义声明被遗漏了。是否有人遇到Asp.Net Identity的同一问题?

0 个答案:

没有答案