Created
April 6, 2021 12:20
-
-
Save martyncoup/83ebf6b78852c677a43226606b46fb9f to your computer and use it in GitHub Desktop.
Gets users and group based role assignment
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Get user role assignments | |
var oid = context.Principal.FindFirstValue("http://schemas.microsoft.com/identity/claims/objectidentifier"); | |
var userRoles = dbContext.RoleMaps.Where(w => w.ObjectId == oid).Join(dbContext.Roles, map => map.RoleId, | |
role => role.Id, (map, role) => new {RoleName = role.Name}).ToList(); | |
// Get group role assignments | |
var groupClaims = context.Principal.Claims.Where(w => w.Type == "groups").Select(s => s.Value).ToList(); | |
var groupRoles = dbContext.RoleMaps.Where(w => groupClaims.Contains(w.ObjectId)).Join(dbContext.Roles, map => map.RoleId, | |
role => role.Id, (map, role) => new { RoleName = role.Name }).ToList(); | |
// Merge lists | |
var roleData = userRoles.Concat(groupRoles).ToList(); | |
// Assign roles to claims, loop for multiple roles | |
if (roleData.Count != 0) | |
{ | |
List<Claim> claims = new List<Claim>(); | |
foreach (var role in roleData) | |
{ | |
claims.Add(new Claim(ClaimTypes.Role, role.RoleName)); | |
} | |
// Assign claim to the identity object | |
var appRoles = new ClaimsIdentity(claims); | |
context.Principal.AddIdentity(appRoles); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment