ASP.NET Core 2.1自定义RoleProvider与Windows身份验证

use*_*570 6 c# roles asp.net-core-mvc asp.net-core asp.net-core-2.0

我正在将应用程序从ASP.Net MVC 5框架迁移到新的.Net Core 2.1.

我在MVC 5项目中使用了Windows身份验证和自定义RoleProvider,如下面的链接所示.

ASP.NET MVC如何创建自定义角色提供程序

如何在Core 2.1中完成相同的操作,因为它似乎不包含RoleProvider功能?

我遇到的每个示例都使用IdentityUser和IdentityRole的个人帐户.

用户和角色的自定义表格:

public class User
{
    public User() { UserRoles = new HashSet<UserRole>(); }

    [Key]
    public string Id { get; set; }

    [StringLength(50)]
    [Required]
    public string Logon { get; set; } //The users Active Directory Username

    public bool Active { get; set; }

    public ICollection<UserRole> UserRoles { get; set; }

}


public class Role
{
    public Role() { UserRoles = new HashSet<UserRole>(); }

    [Key]
    public string Id { get; set; }

    public string Name { get; set; }

    public ICollection<UserRole> UserRoles { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

编辑:

我添加了一个CustomClaimsPrincipal,它类似于:

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));
            //(ApplicationUser)_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)

但它似乎仍然采用原始的ClaimsPrincipal IsInRole函数而不是覆盖,我认为这就是为什么我收到错误消息"主域和可信域之间的信任关系失败".

Ace*_*s25 6

我遇到了同样的问题 - 帖子中给出的解决方案没有帮助,但评论为我指明了正确的方向。您需要向 ClaimsPrincipal 添加声明。

第 1 步:创建 ClaimsTransformer - 替换“Admin”并为您从数据库中获取的每个角色添加单独的声明

using System.Security.Claims;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authentication;

public class ClaimsTransformer : IClaimsTransformation
{ 
    public Task<ClaimsPrincipal> TransformAsync(ClaimsPrincipal principal)
    {
        var ci = (ClaimsIdentity) principal.Identity;
        var c = new Claim(ci.RoleClaimType, "Admin");
        ci.AddClaim(c);
        return Task.FromResult(principal);
    }
}
Run Code Online (Sandbox Code Playgroud)

步骤 2:将您的 ClaimsTransformer 添加到 Startup.cs 的 ConfigureServices 方法

services.AddAuthentication(Microsoft.AspNetCore.Server.IISIntegration.IISDefaults.AuthenticationScheme);
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
services.AddSpaStaticFiles(configuration =>
{
    configuration.RootPath = "ClientApp/dist";
});

services.AddSingleton<IClaimsTransformation, ClaimsTransformer>();
Run Code Online (Sandbox Code Playgroud)

第 3 步:您现在可以在控制器中添加基于角色的授权属性

[Authorize(Roles = "Admin")]
[HttpGet("[action]/{id}")]        
public User GetUser([FromRoute] int id)
{
    UserLogic ul = new UserLogic();
    return ul.GetUser(id);
}
Run Code Online (Sandbox Code Playgroud)

  • 你是如何让这个工作的?我做了同样的事情,我得到“主域和受信任域之间的信任关系失败”? (2认同)
  • @CoderSteve 你有没有弄清楚这一点?我遇到了同样的问题。 (2认同)

ste*_*-fu 4

在网络核心中管理自定义权限通常是通过声明来完成的。您可以通过 aspnet Identity(如何在 ASP.NET Identity 中添加声明)来完成此操作,也可以编写自己的中间件。

一旦您提出索赔,您需要创建保单。这是通过方法Startup.cs中的类完成的ConfigureServices

services.AddAuthorization(options =>
        {
            options.AddPolicy("HR", policy => policy.RequireClaim("HRTeam"));
            options.AddPolicy("Helpdesk", policy => policy.RequireClaim("HelpdeskTeam"));
        });
Run Code Online (Sandbox Code Playgroud)

然后用属性装饰你的控制器/Authorize动作

[Authorize(Policy="Helpdesk")]
public class HelpDeskController : Controller
Run Code Online (Sandbox Code Playgroud)


归档时间:

查看次数:

4852 次

最近记录:

6 年,1 月 前