我正在将应用程序从 ASP.Net MVC 5 框架迁移到新的 .Net Core 2.1。
我在 MVC 5 项目中使用带有自定义 RoleProvider 的 Windows 身份验证,如下面的链接所示。
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; }
}
Edit:
我添加了一个自定义 ClaimsPrincipal ,如下所示:
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;
}
}
并添加到 Startup.cs
services.AddIdentity<ApplicationUser, IdentityRole>().AddEntityFrameworkStores<ApplicationDbContext>();
services.AddScoped<ClaimsPrincipal, CustomClaimsPrincipal>();
但它似乎仍然采用原始的 ClaimsPrincipal IsInRole 函数而不是覆盖,我认为这就是为什么我收到错误消息“主域和受信任域之间的信任关系失败”的原因。