'Querying all users that have a role in Azure Active Directory using MS Graph SDK

I want to query all users in Azure Active Directory who have an app role assigned to.

I am looking for something like this:

private readonly GraphServiceClient _graphServiceClient;

....

var users = await _graphServiceClient.Users
    .Request()
    .Filter(....) <- Here I add the values of the roles, or ids
    .GetAsync();

I only found this solution where I should query all the user, and then for each user check if he has that role assigned. I think it is a solution with a high time and resources consuming. So I am looking for something better, but I did not find anything.

Any suggestions?

PS.: When I say value i mean that:

enter image description here

The image above is from the Owned Application in Azure Active Directory. Those are my custom roles. When I create a custom role I must add also the value.

Via code you can find it with this code:

var application = await _graphServiceClient.Applications["65356eb3-fbd8-428c-bee5-a2da05e55fdb"]
    .Request()
    .Select("appRoles")
    .GetAsync();

enter image description here Thank you



Solution 1:[1]

There should be two ways how to achieve this.

One way is to expand appRoleAssignments relationship and filter app roles by resourceId

https://graph.microsoft.com/v1.0/users?$expand=appRoleAssignments&$filter=appRoleAssignments/any(r:r/resourceId eq {resourceId})&$count=true
Header ConsistencyLevel:eventual

Code

GraphServiceClient graphClient = new GraphServiceClient( authProvider );
var queryOptions = new List<QueryOption>()
{
    new QueryOption("$count", "true")
};

var users = await graphClient.Users
    .Request( queryOptions )
    .Header("ConsistencyLevel","eventual")
    .Filter("appRoleAssignments/any(r:r/resourceId eq {resourceId})")
    .Expand("appRoleAssignments")
    .GetAsync();

Another way is to use $filter in $expand clause

https://graph.microsoft.com/v1.0/users?$expand=appRoleAssignments($filter=resourceId eq {resourceId})

Code

GraphServiceClient graphClient = new GraphServiceClient( authProvider );

var users = await graphClient.Users
    .Request()
    .Expand("appRoleAssignments($filter=resourceId+eq+{resourceId})")
    .GetAsync();

Bad news is that the first way returns BadRequest with error message "Expect simple name=value query, but observe property 'appRoleAssignments' of complex type 'AppRoleAssignment'." which usually means that filtering is not supported.

For the second way the $filter is ignored in $expand clause.

So, what you can do is to get all users with expanded appRoleAssignments and filter users on the client.

var users = await graphClient.Users
    .Expand("appRoleAssignments")
    .GetAsync();

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 user2250152