asp.net-core - 开迪克特。将自定义声明保存到 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设置期间启用......
解决方案
您正在两个不同级别添加声明。
UserManager 寻址存储。它在数据库中查找并保存数据,允许异步实现。另一方面,ClaimsIdentity 未连接到商店。
尽管两者都有 AddClaim 方法,但 UserManager 实际上会保留数据,而 ClaimsIdentity 则不会。
持久声明的想法是,一旦持久,声明应该自动添加到您的 ClaimsIdentity 中。您可能必须自己实现这一点。
推荐阅读
- php - Laravel 类 'App\Http\Controllers\Auth\route' 未找到
- prometheus - 当显示的点数超过 Prometheus 时,Grafana 分辨率的工作原理
- python - 通过 https 运行 python 程序
- nearest-neighbor - 尝试使用点 2D 平面来理解局部敏感散列
- html - 我怎样才能使'ul'居中?
- python - Python cv2 .mp4 编解码器无法在浏览器中显示
- typescript - Apollo graphql 在 useQuery 和 typescript 中使用枚举作为变量
- c - 使用 const 或 define 时,初始化元素在 C 中不是常量
- c# - 如何为 linq 查询的结果创建视图模型以及如何将值传递给视图模型的字段?
- android - 如何为 Webview 设置画中画?