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
Summary
In this post we have seen how to do Azure Active Directory Search using C# & Search Filters.