Search code examples
azuremicrosoft-graph-api

Microsoft Graph: How to filter users by domain name


A tenant can have multiple assigned domains and all users are directly organized within a tenant. To get a list of all users you could simply ask:

https://graph.microsoft.com/v1.0/users

But I'd like to filter the list by the used domain within the user principal name. After reading the explanation at MSDN and the developer documentation it seems that it is not possible to do something like this.

You can only check for (not) equality or if a string starts with some text, but it is not possible to check if a string ends with something specific.

I wish there would exists something like, but neither is:

https://graph.microsoft.com/v1.0/users?$filter=endsWith(userPrincipalName, 'mydomain.com')
https://graph.microsoft.com/v1.0/users?$filter=userPrincipalName eq '*@mydomain.com'
https://graph.microsoft.com/v1.0/users?$filter=userPrincipalName eq '.*@mydomain.com$'
https://graph.microsoft.com/v1.0/users?$filter=domain eq 'mydomain.com'
https://graph.microsoft.com/v1.0/users?$search="userPrincipalName:mydomain.com"

Does anyone have an idea on how to filter the list of users for a specific domain?


Solution

  • endsWith is working since recently.

    Graph explorer example:

    https://graph.microsoft.com/v1.0//users?$count=true&$filter=endsWith(userPrincipalName,'@example.com')&$select=id,userPrincipalName
    

    Graph.NET SDK:

    var request = graphServiceClient.Users
                    .Request()
                    .Header("ConsistencyLevel", "eventual")
                    .Filter("endswith(userPrincipalName,'@example.com')")
                    .Select(x => new { x.Id, x.UserPrincipalName })
                    .OrderBy("userPrincipalName");
    request.QueryOptions.Add(new QueryOption("$count", "true"));
    
    var result = await request.GetAsync();
    

    See also example 5 at https://learn.microsoft.com/en-us/graph/api/user-list?view=graph-rest-1.0&tabs=csharp (at this moment the C# example in the docs is incomplete)