ASP.NET 核心 MVC 自定义身份属性

ASP.NET Core MVC custom identity properties

我正在尝试在 ASP.NET 核心 MVC 中构建一个网站,并且正在使用 Microsoft.Identity 库。我的 User (ApplicationUser) class 中有一个自定义 属性,称为 Token。我想在使用该令牌登录时创建一个 cookie。所以我需要调用一些函数,允许我从登录用户获取 Token 属性(通过 UserManager 或其他任何方式。它必须是登录的用户。)

我在 Internet 上搜索并通过创建自定义工厂然后将其添加到 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 的方法,但找不到访问它的方法。

您的 "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);

希望这对您有所帮助。