在标识 3 中创建声明标识



Visual Studio 2015 基架使用不能用于创建ClaimsIdentityUserManager<TUser>。有没有人有关于如何做到这一点的工作示例?

VS2015 脚手架引发错误:

public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager)
{
    // Note the authenticationType must match the one 
    // defined in CookieAuthenticationOptions.AuthenticationType
    var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
    // Add custom user claims here
    return userIdentity;
}

注意:我为ApplicationUser添加了与IdentyUser不冲突的属性。

UserManager 在 MVC6 版本中已更改。您将需要修改代码...

public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager) {
    var authenticationType = "Put authentication type Here";
    var userIdentity = new ClaimsIdentity(await manager.GetClaimsAsync(this), authenticationType);
    // Add custom user claims here
    return userIdentity;
}

.net core

答案已经改变,根据这里和这里,两位作者都陈述了使用 UserClaimsPrincipalFactory<ApplicationUser> 这是 Core 2.2 的默认实现。第一篇文章说您要查找的方法已移动。但是,如前所述,您必须在此类服务中注册UserClaimsPrincipalFactory的实现,下面是一个示例类实现。请注意,我们必须注册MyUserClaimsPrincipalFactory以便我们的服务集合知道在哪里可以找到它。这意味着在SignInManager<ApplicationUser>的构造函数中它也引用IUserClaimsPrincipalFactory<ApplicationUser>但服务将解决它:

services
.AddIdentity<ApplicationUser, ApplicationRole>()              
.AddClaimsPrincipalFactory<MyUserClaimsPrincipalFactory>() // <======== HERE
services.AddScoped<IUserClaimsPrincipalFactory<ApplicationUser>, MyUserClaimsPrincipalFactory>();

这是下面的类:

public class MyUserClaimsPrincipalFactory : UserClaimsPrincipalFactory<ApplicationUser>
{
    public MyUserClaimsPrincipalFactory(UserManager<ApplicationUser> userManager, 
        IOptions<IdentityOptions> optionsAccessor)
        : base(userManager, optionsAccessor)
    {
    }
    protected override async Task<ClaimsIdentity> GenerateClaimsAsync(ApplicationUser user)
    {
        var identity = await base.GenerateClaimsAsync(user);
        identity.AddClaim(new Claim("ContactName", "John Smith"));
        return identity;
    }
}

最新更新