Azure AD Search using C#

In this post I would like to give a Sample to Search on Azure Active Directory using Filter.

Pre-Requisites

Following are the pre-requisites:

  • Create AD > App Registration & Client Credentials
  • Assign Directory.Read.All “application” permission & Provide Admin Consent

The Code

private async static void SerachAzureAD(string search)
        {
                string clientID = “YOUR-CLIENT-ID”;
                string clientSecret = “YOUR-CLIENT-SECRET”;
                string tenantID = “YOUR-AD-TENANT-ID”;

               string graphApiResource = “https://graph.microsoft.com”;
                Uri microsoftLogin = new Uri(“https://login.microsoftonline.com/”);

               string authority = new Uri(microsoftLogin, tenantID).AbsoluteUri;
                AuthenticationContext authenticationContext = new AuthenticationContext(authority);
                ClientCredential clientCredential = new ClientCredential(clientID, clientSecret);

               // Picks up the bearer token.
                AuthenticationResult authenticationResult = authenticationContext.AcquireTokenAsync(graphApiResource, clientCredential).Result;

               GraphServiceClient graphClient = new GraphServiceClient(new DelegateAuthenticationProvider(
                async (requestMessage) =>
                {
                    requestMessage.Headers.Authorization = new AuthenticationHeaderValue(“bearer”, authenticationResult.AccessToken);
                }));

               string filter = $”startswith(displayName, ‘{search}’) or startswith(givenName, ‘{search}’) or startswith(surname, ‘{search}’) or startswith(mail, ‘{search}’) or startswith(userPrincipalName, ‘{search}’)”;
                //$”$filter=displayName EQ {search}”;

               IGraphServiceUsersCollectionPage users = graphClient.Users.Request()
                    .Filter(filter)
                    .GetAsync().Result;

               Console.WriteLine(“Searching..”);

               while (users.Count > 0)
                {
                    foreach (var user in users.CurrentPage)
                    {
                        Console.WriteLine(user.DisplayName);
                    }

                   if (users.NextPageRequest != null)
                    {
                        users = await users.NextPageRequest
                            .GetAsync();
                    }
                    else
                    {
                        break;
                    }
                }

        }

Result

image

Summary

In this post we have seen how to do Azure Active Directory Search using C# & Search Filters.

Advertisement

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s