在我的ASP.NET Core应用程序中,我创建了两个角色:
Company
是我的数据库中的一个实体。
任何用户都可以创建Company
并成为其公司管理员。
但是,如果一个用户为另一个Company
提供了作为CompanyViewer的另一用户访问权限,则将不允许新用户管理此Company
中的用户。
因此,作为用户,我可以访问许多公司。其中有些我将成为管理员,而另一些我将成为查看者。
还会有其他用户创建的公司,而我将没有任何访问权限。
问题是:如何将特定角色与用户和公司同时关联?
现在我有一些代码:
用户模型:
public class ApplicationUser : IdentityUser
{
public virtual IList<CompanyUser> Companies { get; set; }
}
公司模式:
public class Company
{
public long ID { get; set; }
[Display(Name = "Title")]
public string Title { get; set; }
[Display(Name = "Users")]
public virtual IList<CompanyUser> Users { get; set; }
}
控制关系的模型(我将其重命名为CompanyPermission):
public class CompanyUser
{
[ForeignKey("Company")]
public long CompanyID { get; set; }
public Company Company { get; set; }
[ForeignKey("ApplicationUser")]
[MaxLength(450)]
public string UserID { get; set; }
public ApplicationUser User { get; set; }
public CompanyUserRole Role { get; set; }
}
public enum CompanyUserRole
{
Administrator = 1,
Viewer = 2
}
我如何检查某些服务对象是否具有编辑公司的权限:
ApplicationUser appUser = await _userManager.GetUserAsync(User);
var currentCompany = await _context.Company.Include(c => c.Users).SingleOrDefaultAsync(m => m.ID == id);
if (!currentCompany.Users.Where(c => c.UserID == appUser.Id && c.Role == CompanyUserRole.Administrator).Any())
{
return NotFound();
}
我如何创建要使用的角色,而不是上面的代码:
var companyAdminRole = await _roleManager.FindByNameAsync("CompanyAdmin");
if (companyAdminRole == null)
{
companyAdminRole = new IdentityRole("CompanyAdmin");
await _roleManager.CreateAsync(companyAdminRole);
await _roleManager.AddClaimAsync(companyAdminRole, new Claim("Permission", "company.view"));
await _roleManager.AddClaimAsync(companyAdminRole, new Claim("Permission", "company.update"));
await _roleManager.AddClaimAsync(companyAdminRole, new Claim("Permission", "company.users.view"));
await _roleManager.AddClaimAsync(companyAdminRole, new Claim("Permission", "company.users.manage"));
await _roleManager.AddClaimAsync(companyAdminRole, new Claim("Permission", "company.analitycs.view"));
await _roleManager.AddClaimAsync(companyAdminRole, new Claim("Permission", "company.analitycs.download"));
}
var companyViewerRole = await _roleManager.FindByNameAsync("CompanyViewer");
if (companyViewerRole == null)
{
companyViewerRole = new IdentityRole("CompanyViewer");
await _roleManager.CreateAsync(companyViewerRole);
await _roleManager.AddClaimAsync(companyViewerRole, new Claim("Permission", "company.view"));
await _roleManager.AddClaimAsync(companyViewerRole, new Claim("Permission", "company.analitycs.view"));
await _roleManager.AddClaimAsync(companyViewerRole, new Claim("Permission", "company.analitycs.download"));
}