ASP.Net Core 2.1注册自定义ClaimsPrincipal

use*_*570 3 c# asp.net-identity asp.net-core

我正在创建一个Windows身份验证应用程序,但角色位于自定义数据库中,而不是AD上,因此我创建了一个自定义的ClaimsPrincipal来覆盖通常在AD中查看角色的User.IsInRole()函数.

但是,在运行应用程序时,它似乎仍然使用原始代码而不是我的CustomClaimsPrincipal.我收到错误"主域和受信任域之间的信任关系失败".

在ASP.Net MVC 5中,我使用了一个Custom RoleProvider,它本质上是我试图在这里复制的.

CustomClaimsPrincipal.cs

public class CustomClaimsPrincipal : ClaimsPrincipal
{
    private readonly ApplicationDbContext _context;

    public CustomClaimsPrincipal(ApplicationDbContext context)
    {
        _context = context;
    }

    public override bool IsInRole(string role)
    {
        var currentUser = ClaimsPrincipal.Current.Identity.Name;

        IdentityUser user = _context.Users.FirstOrDefault(u => u.UserName.Equals(currentUser, StringComparison.CurrentCultureIgnoreCase));

        var roles = from ur in _context.UserRoles.Where(p => p.UserId == user.Id)
                    from r in _context.Roles
                    where ur.RoleId == r.Id
                    select r.Name;
        if (user != null)
            return roles.Any(r => r.Equals(role, StringComparison.CurrentCultureIgnoreCase));
        else
            return false;
    }
}
Run Code Online (Sandbox Code Playgroud)

Startup.cs

        services.AddIdentity<ApplicationUser, IdentityRole>().AddEntityFrameworkStores<ApplicationDbContext>();

        services.AddScoped<ClaimsPrincipal,CustomClaimsPrincipal>();
Run Code Online (Sandbox Code Playgroud)

不确定Startup.cs中的上述代码是否是覆盖ClaimsPrincipal的正确方法,因为我是.Net Core框架的新手.

Mic*_*iey 15

我想我会以不同的方式解决这个问题:我不是试图让ClaimsPrincipal数据库的谈话实例来确定它们是否属于某个特定的角色,而是ClaimsPrincipalClaimsPrincipal实例中修改并添加它们所属的角色.

为此,我会使用一个遗憾的是没有详细记录的功能.身份验证管道公开了一个可扩展点,一旦完成身份验证,您就可以转换ClaimsPrincipal已创建的实例.这可以通过IClaimsTransformation界面完成.

代码看起来像:

public class Startup
{
    public void ConfigureServices(ServiceCollection services)
    {
        // Here you'd have your registrations

        services.AddTransient<IClaimsTransformation, ClaimsTransformer>();
    }
}

public class ClaimsTransformer : IClaimsTransformation
{
    private readonly ApplicationDbContext _context;

    public ClaimsTransformer(ApplicationDbContext context)
    {
        _context = context;
    }

    public async Task<ClaimsPrincipal> TransformAsync(ClaimsPrincipal principal)
    {
        var existingClaimsIdentity = (ClaimsIdentity)principal.Identity;
        var currentUserName = existingClaimsIdentity.Name;

        // Initialize a new list of claims for the new identity
        var claims = new List<Claim>
        {
            new Claim(ClaimTypes.Name, currentUserName),
            // Potentially add more from the existing claims here
        };

        // Find the user in the DB
        // Add as many role claims as they have roles in the DB
        IdentityUser user = await _context.Users.FirstOrDefaultAsync(u => u.UserName.Equals(currentUserName, StringComparison.CurrentCultureIgnoreCase));
        if (user != null)
        {
            var rolesNames = from ur in _context.UserRoles.Where(p => p.UserId == user.Id)
                        from r in _context.Roles
                        where ur.RoleId == r.Id
                        select r.Name;

            claims.AddRange(rolesNames.Select(x => new Claim(ClaimTypes.Role, x)));
        }

        // Build and return the new principal
        var newClaimsIdentity = new ClaimsIdentity(claims, existingClaimsIdentity.AuthenticationType);
        return new ClaimsPrincipal(newClaimsIdentity);
    }
}
Run Code Online (Sandbox Code Playgroud)

对于完全公开,该TransformAsync方法将在每次身份验证过程发生时运行,因此很可能在每个请求上运行,这也意味着它将在每次请求时查询数据库以获取登录用户的角色.

使用此解决方案而不是修改实现的优势ClaimsPrincipal在于,ClaimsPrincipal它现在变得愚蠢而且与数据库无关.只有身份验证管道知道它,这使得测试变得更容易,例如,ClaimsPrincipal使用特定角色来新建a 以确保它们可以访问特定操作,或者无法访问特定操作,而不必绑定到数据库.