public static bool IsAuthorized(ClientPrincipal clientPrincipal, string targetUserId) { var principal = CreateClaimPrincipal(clientPrincipal); var roles = principal.Claims.Where(claim => claim.Type == ClaimTypes.Role); if (!roles.Any()) { return(false); } var loggedInUserId = principal.Claims.FirstOrDefault(claim => claim.Type == ClaimTypes.NameIdentifier)?.Value; return(loggedInUserId == targetUserId); }
public static ClaimsPrincipal CreateClaimPrincipal(ClientPrincipal principal) { if (!principal.UserRoles.Any()) { return(new ClaimsPrincipal()); } principal.UserRoles = principal.UserRoles.Except(new string[] { "anonymous" }, StringComparer.CurrentCultureIgnoreCase); var identity = new ClaimsIdentity(principal.IdentityProvider); identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, principal.UserId)); identity.AddClaim(new Claim(ClaimTypes.Name, principal.UserDetails)); identity.AddClaims(principal.UserRoles.Select(r => new Claim(ClaimTypes.Role, r))); return(new ClaimsPrincipal(identity)); }