【问题标题】:ASP.NET Core MVC custom identity propertiesASP.NET Core MVC 自定义标识属性
【发布时间】: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


【解决方案1】:

您的“CustomUserIdentityFactory”向登录用户添加声明,以便将声明添加到 cookie 中,可以通过指定声明类型使用“User.Claims”访问。

假设您的声明类型是“http://www.example.com/ws/identity/claims/v1/token

通过使用您自己的声明类型覆盖“CreateAsync”方法来更改您的代码,如下所示。

public override async Task<ClaimsPrincipal> CreateAsync(User user) {
            var principal = await base.CreateAsync(user);
            var tokenClaimType = "http://www.example.com/ws/identity/claims/v1/token"

            if(!string.IsNullOrWhiteSpace(user.Token)) {
                ((ClaimsIdentity)principal.Identity).AddClaims(new[] {
                    new Claim(tokenClaimType, user.Token)
                });
            }

            return principal;
        }

如何在"User.Claims" 中访问令牌

var tokenClaimType = "http://www.example.com/ws/identity/claims/v1/token"
var token = User.Claims.Where(claim => claim.Type == tokenClaimType);

希望这会有所帮助。

【讨论】:

    猜你喜欢
    • 2018-09-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多