【发布时间】:2018-12-09 17:20:30
【问题描述】:
在AuthController 进行身份验证时,我创建了一些声明 - UserID 就是其中之一。
...
Subject = new ClaimsIdentity(new[]
{
new Claim(ClaimTypes.Name, user.UserName),
new Claim("UserID", user.Id.ToString()),
})
当 Angular 应用发出请求时,我可以在另一个控制器中获取 UserID
Claim claimUserId = User.Claims.SingleOrDefault(c => c.Type == "UserID");
ControllerBase.User 实例持有 .Identity 对象,而该对象又持有 Claims 集合。
Identity.IsAuthenticated等于True。Identity.Name包含admin字符串(相关用户的名称)。
如果我尝试这样获取用户:
var user = await UserManager.GetUserAsync(HttpContext.User)
user 是 null。
也许,我忘了添加一些额外的声明?
或者,也许,一旦我使用 JWT - 我应该覆盖默认的 UserManager 功能,以便它通过包含 UserID 的 claim 获取用户?
或者也许有更好的方法?
附加信息:
Identity注册如下
services.AddIdentity<ApplicationUser, ApplicationRole>()
.AddEntityFrameworkStores<AppDbContext>()
.AddDefaultTokenProviders();
ApplicationUser.Id 字段是 bigint(或在 C# 中为 long)类型
另外,我在 EF Seed Data 中使用 UserManager 创建用户,使用 ServiceProvider 解决
_userManager = scope.ServiceProvider.GetService<UserManager<ApplicationUser>>();
...
adminUser.PasswordHash = new PasswordHasher<ApplicationUser>().HashPassword(adminUser, "123qwe");
_userManager.CreateAsync(adminUser);
【问题讨论】:
-
您能分享一下您是如何注册身份的吗?
-
嗨@AlexRiabov,刚刚回答了你的问题,
Additional Info部分下的代码。
标签: c# asp.net-core asp.net-identity claims-based-identity