I've created an Azure active directory user and added the user to app roles. Now i am retrieving this user and attempting to add it to more app roles.

var activeDirectoryUser = client.Users.Where(u => u.UserPrincipalName == user.UserName).ExecuteSingleAsync().Result as User;

As a precaution i want to first check if the user is already in an app role before adding however the problem is that the ApproleAssignments field on the User object is always empty. Even thou the user has app role assignments and i get an error if i try and add the user to the same app role.

Creating new app role assignment.

var appRoleAssignment = new AppRoleAssignment
        {
            Id = appRole.Id,
            ResourceId = Guid.Parse(servicePrincpal.ObjectId),
            PrincipalType = "User",
            PrincipalId = Guid.Parse(user.ObjectId)
        };

if(IsUserInAppRole(user,appRoleAssignment))return;

user.AppRoleAssignments.Add(appRoleAssignment);
user.UpdateAsync().Wait();

Checking if user is in app role.

private bool IsUserInAppRole(User user, AppRoleAssignment appRoleAssignment)
    {
        var userInApprole = user.AppRoleAssignments.Where(ara => ara.ObjectId == appRoleAssignment.Id.ToString());
        return userInApprole.Any();
    }

I'm using the latest version of Microsoft.Azure.ActiveDirectory.GraphClient library

Related posts

Recent Viewed