首页 > 解决方案 > 开迪克特。将自定义声明保存到 AspNetUserClaims 表

问题描述

我有一个基于 openiddict 2.0 的身份验证服务器。我需要的是添加自定义声明。经过一番搜索,我来到了自定义实现UserClaimsPrincipalFactory

public class CustomUserClaimsPrincipalFactory : UserClaimsPrincipalFactory<ApplicationUser, IdentityRole>
{
    public CustomUserClaimsPrincipalFactory(
        UserManager<ApplicationUser> userManager,
        RoleManager<IdentityRole> roleManager,
        IOptions<IdentityOptions> optionsAccessor)
        : base(userManager, roleManager, optionsAccessor)
    {
    }

    protected override async Task<ClaimsIdentity> GenerateClaimsAsync(ApplicationUser user)
    {
        var customClaim = new Claim("demo", "some value");

        var identity = await base.GenerateClaimsAsync(user);
        identity.AddClaim(customClaim);            
        return identity;
    }
}

它可以工作,并且“演示”声明被添加到令牌中,并且可以User.Claims从控制器操作中获得(我正在使用 OAuth2 验证中间件)。唯一令人困惑的一件事是带有该声明的记录未添加到AspNetUserClaims表中。我发现我可以通过以下方式将其直接添加到GenerateClaimsAsync方法中来“修复”这个问题:

await UserManager.AddClaimAsync(user, customClaim);

现在我想知道这是正确的方法,还是有一些简单的配置步骤,也许像“选项”标志,我只需要在openiddict设置期间启用......

标签: asp.net-coreclaimsopeniddict

解决方案


您正在两个不同级别添加声明。

UserManager 寻址存储。它在数据库中查找并保存数据,允许异步实现。另一方面,ClaimsIdentity 未连接到商店。

尽管两者都有 AddClaim 方法,但 UserManager 实际上会保留数据,而 ClaimsIdentity 则不会。

持久声明的想法是,一旦持久,声明应该自动添加到您的 ClaimsIdentity 中。您可能必须自己实现这一点。


推荐阅读