简体   繁体   中英

Implementing Group-Based Roles ASP.NET MVC CORE

i want to Implementing Group-Based Permissions Roles Management, Every user have one group and that group have roles . i did that with ASP.NET MVC depending on this > http://johnatten.com/2014/08/10/asp-net-identity-2-0-implementing-group-based-permissions-management/

the problem ApplicationRoles cannot make relation with group roles its return 0 count of roles . so cannot clear roles or get group roles .

public virtual ICollection<ApplicationGroupRole> ApplicationRoles { get; set; }

 public class ApplicationUserRole : IdentityUserRole<string> { }

public class ApplicationUser : IdentityUser
{

    public ApplicationUser()
    {
        Id = Guid.NewGuid().ToString();

        // Add any custom User properties/code here
    }


}
// Must be expressed in terms of our custom UserRole:
public class ApplicationRole : IdentityRole
{
    public ApplicationRole()
    {
        Id = Guid.NewGuid().ToString();
    }

    public ApplicationRole(string name)
        : this()
    {
        Name = name;
    }

    // Add any custom Role properties/code here
}


public class ApplicationDbContext : IdentityDbContext<ApplicationUser, ApplicationRole, string, IdentityUserClaim<string>,
    ApplicationUserRole, IdentityUserLogin<string>,
    IdentityRoleClaim<string>, IdentityUserToken<string>>
{


    public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options) : base(options)
    {
    }

    public virtual DbSet<ApplicationGroup> ApplicationGroups { get; set; }

    protected override void OnModelCreating(ModelBuilder builder)
    {
        // Customize the ASP.NET Identity model and override the defaults if needed.
        // For example, you can rename the ASP.NET Identity table names and more.
        // Add your customizations after calling base.OnModelCreating(builder);

  base.OnModelCreating(builder);

        builder.Entity<ApplicationGroup>()
            .HasMany(g => g.ApplicationUsers).WithOne()
            .HasForeignKey(ag => ag.ApplicationGroupId).IsRequired();

        builder.Entity<ApplicationGroup>()
            .HasMany(g => g.ApplicationRoles)
            .WithOne().HasForeignKey(ap => ap.ApplicationGroupId).IsRequired();


        builder.Entity<ApplicationUserGroup>().ToTable("ApplicationUserGroups")
            .HasKey(r =>
                new
                {
                    r.ApplicationUserId,
                    r.ApplicationGroupId
                });

        builder.Entity<ApplicationGroupRole>().ToTable("ApplicationGroupRoles")
            .HasKey(gr =>
            new
            {
                gr.ApplicationRoleId,
                gr.ApplicationGroupId
            });


        builder.Entity<ApplicationGroup>().ToTable("ApplicationGroups")
            .Property(x => x.Id).HasColumnName("Id");
        builder.Entity<ApplicationGroup>().ToTable("ApplicationGroups")
            .Property(x => x.Name).HasColumnName("Name");
        builder.Entity<ApplicationGroup>().ToTable("ApplicationGroups")
            .Property(x => x.Description).HasColumnName("Description");


        builder.Entity<ApplicationUserGroup>().ToTable("ApplicationUserGroups")
            .Property(x => x.ApplicationUserId).HasColumnName("ApplicationUserId");
        builder.Entity<ApplicationUserGroup>().ToTable("ApplicationUserGroups")
            .Property(x => x.ApplicationGroupId).HasColumnName("ApplicationGroupId");


        builder.Entity<ApplicationGroupRole>().ToTable("ApplicationGroupRoles")
            .Property(x => x.ApplicationRoleId).HasColumnName("ApplicationRoleId");
        builder.Entity<ApplicationGroupRole>().ToTable("ApplicationGroupRoles")
            .Property(x => x.ApplicationGroupId).HasColumnName("ApplicationGroupId");





    }


}

public class ApplicationGroup
{
    public ApplicationGroup()
    {
        Id = Guid.NewGuid().ToString();
        ApplicationRoles = new List<ApplicationGroupRole>();
        ApplicationUsers = new List<ApplicationUserGroup>();
    }

    public ApplicationGroup(string name)
        : this()
    {
        Name = name;
    }

    public ApplicationGroup(string name, string description)
        : this(name)
    {
        Description = description;
    }

    [Key]
    public string Id { get; set; }
    [Required]
    public string Name { get; set; }
    public string Description { get; set; }

    public virtual ICollection<ApplicationGroupRole> ApplicationRoles { get; set; }
    public virtual ICollection<ApplicationUserGroup> ApplicationUsers { get; set; }
}

public class ApplicationUserGroup
{
    public string ApplicationUserId { get; set; }
    public string ApplicationGroupId { get; set; }
}

public class ApplicationGroupRole
{
    public string ApplicationGroupId { get; set; }
    public string ApplicationRoleId { get; set; }
}

when i edit group roles there's exception

SqlException: Violation of PRIMARY KEY constraint 'PK_dbo.ApplicationGroupRoles'. Cannot insert duplicate key in object 'dbo.ApplicationGroupRoles'. The duplicate key value is (7f742999-023c-43e4-9a6a-ccef6f89765b). The statement has been terminated.

that happens because the roles must clear before add again.

    public async Task<IdentityResult> SetGroupRoles(string groupId, params string[] roleNames)
    {
        // Clear all the roles associated with this group:
        var thisGroup = FindById(groupId);

        thisGroup.ApplicationRoles.Clear();


        _db.SaveChanges();

        // Add the new roles passed in:
        var newRoles = _roleManager.Roles.Where(r => roleNames.Any(n => n == r.Name));
        foreach (var role in newRoles)
        {
            thisGroup.ApplicationRoles.Add(new ApplicationGroupRole { ApplicationGroupId = groupId, ApplicationRoleId = role.Id });
        }
        _db.SaveChanges();

        // Reset the roles for all affected users:
        var groupUsers = GetGroupUsersAsync(groupId).Result.ToList();
        foreach (var groupUser in groupUsers)
        {
            await   RefreshUserGroupRolesAsync(groupUser.Id);
        }
        return IdentityResult.Success;
    }

Check your table relationships. They should be similar to the following:

       ApplicationRoles
       PK AppRoleId

       ApplicationGroups
       PK AppGroupId

       ApplicationGroupRoles -Junction Table
       PK AppRoleId FK
       PK AppGroupId FK

Make sure the two fields in the juction table are both the primary key and the foreign key. Based on the error, it looks like you're missing the foreign key constraint.

您可以在 asp 核心中使用身份 4 并使用声明和 RoleClaims 模型

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM