Ale*_*man 11 c# claims-based-identity asp.net-identity asp.net-core
在AuthController
身份验证时,我创建了几个声明 - UserID
就是其中之一.
...
Subject = new ClaimsIdentity(new[]
{
new Claim(ClaimTypes.Name, user.UserName),
new Claim("UserID", user.Id.ToString()),
})
Run Code Online (Sandbox Code Playgroud)
当Angular应用程序发出请求时,我可以UserID
在另一个控制器中获取
Claim claimUserId = User.Claims.SingleOrDefault(c => c.Type == "UserID");
Run Code Online (Sandbox Code Playgroud)
该ControllerBase.User
实例包含.Identity
对象则持有Claims
集合.
Identity.IsAuthenticated
等于True
.
Identity.Name
保存admin
字符串(相关用户的名称).
如果我尝试像这样获取用户:
var user = await UserManager.GetUserAsync(HttpContext.User)
Run Code Online (Sandbox Code Playgroud)
的user
是null
.
也许,我忘了添加一些额外的索赔?
或者,也许,一旦我使用JWT - 我应该覆盖默认UserManager
功能,以便它获取用户claim
保持UserID
?
或者可能有更好的方法?
附加信息:
该Identity
注册如下
services.AddIdentity<ApplicationUser, ApplicationRole>()
.AddEntityFrameworkStores<AppDbContext>()
.AddDefaultTokenProviders();
Run Code Online (Sandbox Code Playgroud)
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);
Run Code Online (Sandbox Code Playgroud)
pok*_*oke 24
UserManager.GetUserAsync
内部用于UserManager.GetUserId
检索用户的用户ID,然后用于从用户存储(即您的数据库)查询对象.
GetUserId
基本上看起来像这样:
public string GetUserId(ClaimsPrincipal principal)
{
return principal.FindFirstValue(Options.ClaimsIdentity.UserIdClaimType);
}
Run Code Online (Sandbox Code Playgroud)
所以这会返回索赔值Options.ClaimsIdentity.UserIdClaimType
.Options
是您配置标识的IdentityOptions
对象.默认情况下的数值UserIdClaimType
是ClaimTypes.NameIdentifier
,即"http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier"
.
因此,当您尝试使用UserManager.GetUserAsync(HttpContext.User)
该用户主体UserID
声明的用户时,用户管理员只是在寻找不同的声明.
你可以通过切换到ClaimTypes.NameIdentifier
:
new ClaimsIdentity(new[]
{
new Claim(ClaimTypes.Name, user.UserName),
new Claim(ClaimTypes.NameIdentifier, user.Id.ToString()),
})
Run Code Online (Sandbox Code Playgroud)
或者您正确配置身份,以便它将使用您的UserID
声明类型:
// in Startup.ConfigureServices
services.AddIdentity(options => {
options.ClaimIdentity.UserIdClaimType = "UserID";
});
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
3943 次 |
最近记录: |