【发布时间】:2017-12-14 16:35:10
【问题描述】:
我正在尝试在 ASP.NET Core MVC 中构建网站并使用 Microsoft.Identity 库。我的User (ApplicationUser) 类中有一个自定义属性,称为Token。我想使用该令牌在登录时创建一个 cookie。所以我需要调用一些函数,允许我从登录用户那里获取Token 属性(通过 UserManager 或其他方式。它必须是登录的用户。)
我在互联网上搜索并通过创建自定义工厂然后将其添加到 startup.cs Like this 找到了几种解决方案。但我找不到或看不到进入该物业的方法。 User.Identity.GetToken() 不起作用。
这是我的自定义工厂:
public class CustomUserIdentityFactory : UserClaimsPrincipalFactory<User, IdentityRole>
{
public CustomUserIdentityFactory(UserManager<User> userManager, RoleManager<IdentityRole> roleManager, IOptions<IdentityOptions> optionsAccessor) : base(userManager, roleManager, optionsAccessor)
{}
public override async Task<ClaimsPrincipal> CreateAsync(User user) {
var principal = await base.CreateAsync(user);
if(!string.IsNullOrWhiteSpace(user.Token)) {
((ClaimsIdentity)principal.Identity).AddClaims(new[] {
new Claim(ClaimTypes.Hash, user.Token)
});
}
return principal;
}
}
这是我Startup.cs中的配置
services.AddScoped<IUserClaimsPrincipalFactory<User>, CustomUserIdentityFactory>();
所以,长话短说:我正在尝试访问自定义身份属性,并找到了将其添加到 UserManager 的方法,但找不到访问它的方法。
【问题讨论】:
-
我通过在用户登录后通过使用
(await _userManager.GetUserAsync(HttpContext.User)).Token获取用户来设置cookie来获得解决方法
标签: c# asp.net-core asp.net-core-mvc asp.net-core-1.1 asp.net-core-identity