mo-esmp / DynamicRoleBasedAuthorizationNETCore

Dynamic Role-Based Access Control for ASP.NET Core MVC and Web API
GNU General Public License v3.0
451 stars 94 forks source link

Pulll: Adding Claims to Role - to create a sub group #16

Closed papyr closed 3 years ago

papyr commented 3 years ago

Hello, I am trying add role-claims to your code, can you please pull this and help me if its correct.

Use Case: we need create groups for data access inside a role. And, right now I have role for manager but I want limit the managers data access to sallies, budgets etc. based on their area like state or city or region.

So EastCoast-Managers, WestCoast-Managers etc. can only see salaries in their areas. I am trying the code below, but I don't know how to create those groups like in Active Directory

public async Task<ActionResult> UpdateRole(string id, string name, List<KeyValuePair<string, string>> claims)
        {
            try
            {
                var role = await _roleManager.FindByIdAsync(id);
                if (role == null)
                    return NotFound("mo esmp for Role not found.");

                role.Name = name;

                var result = await _roleManager.UpdateAsync(role);
                if (result.Succeeded)
                {
                    _logger.LogInformation("Updated role {name}.", role.Name);

                    var roleClaims = await _roleManager.GetClaimsAsync(role);

                    foreach (var kvp in claims.Where(a => !roleClaims.Any(b => _claimTypes[a.Key] == b.Type && a.Value == b.Value)))
                        await _roleManager.AddClaimAsync(role, new Claim(_claimTypes[kvp.Key], kvp.Value));

                    foreach (var claim in roleClaims.Where(a => !claims.Any(b => a.Type == _claimTypes[b.Key] && a.Value == b.Value)))
                        await _roleManager.RemoveClaimAsync(role, claim);

                    return NoContent();
                }
                else
                    return BadRequest(result.Errors.First().Description);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Failure updating role {roleId}.", id);
                return StatusCode(StatusCodes.Status500InternalServerError, ex.Message);
            }
        }