Azure AD – Retrieving Group Members

Recently I needed to query Azure AD from a web api to retrieve members of an AD group, this was prototyped in a console app – C#.

Got the following packages from Nuget…

using Microsoft.Azure.ActiveDirectory.GraphClient;
using Microsoft.IdentityModel.Clients.ActiveDirectory;
using Microsoft.Azure.ActiveDirectory.GraphClient.Extensions;

Declared my constants – I created a new application from within the Azure Management Portal (Active Directory Area), this allowed me to get a client ID and client Secret – required for authentication.

public class Constants
{
public const string auth = "https://login.windows.net/MYDOMAIN.onmicrosoft.com";
public const string clientID = "client ID GUID";
public const string clientSecret = "client SECRET GUID";
public const string azureGraphAPI = "https://graph.windows.net";
public const string serviceRoot = "https://graph.windows.net/MYDOMAIN.onmicrosoft.com";
}

Created a method to instantiate ActiveDirectoryClient – essentially creating a connection to Azure AD.

private static async Task<string> GetAzureAdToken()
{
AuthenticationContext authenticationContext = new AuthenticationContext(Constants.auth, true);
ClientCredential clientCred = new ClientCredential(Constants.clientID, Constants.clientSecret);
AuthenticationResult authenticationResult = await authenticationContext.AcquireTokenAsync(Constants.azureGraphAPI, clientCred);
return authenticationResult.AccessToken;
}

And wrote another two methods allowing me to get a single user by querying using a UPN, and another method to allow me to retrieve a group and its members based on the group name.

private static async Task<string> GetUser(ActiveDirectoryClient adClient, string Upn)
{
var userLookupTask = adClient.Users.Where(x => x.UserPrincipalName.Equals(Upn, StringComparison.CurrentCultureIgnoreCase)).ExecuteSingleAsync();

User me = (User)await userLookupTask;
Console.WriteLine(me.DisplayName);
return me.DisplayName;
}

private static async Task<string> GetGroup(ActiveDirectoryClient adClient, string GroupName)
{
var groupLookup = adClient.Groups.Where(x => x.DisplayName.Equals(GroupName, StringComparison.CurrentCultureIgnoreCase)).ExecuteSingleAsync();

Group grp = (Group)await groupLookup;
IGroupFetcher groupFetcher = (IGroupFetcher)grp;
IPagedCollection<IDirectoryObject> members = groupFetcher.Members.ExecuteAsync().Result;

do
{
List<IDirectoryObject> directoryObjects = members.CurrentPage.ToList();
foreach (IDirectoryObject member in directoryObjects)
{
if (member is User)
{
User usr = member as User;
Console.WriteLine("user: {0} : {1} : {2}", usr.DisplayName, usr.TelephoneNumber, usr.Mobile);
}
}
members = members.MorePagesAvailable ? members = members.GetNextPageAsync().Result : null;

} while (members != null);

return grp.DisplayName;
}

Within my Main method, it was a case of connecting to Azure AD, and calling the methods…

class Program
{
static void Main(string[] args)
{
try
{
Uri serviceRoot = new Uri(Constants.serviceRoot);
ActiveDirectoryClient adContext = new ActiveDirectoryClient(serviceRoot,async () => await GetAzureAdToken());

var user = GetUser(adClient, "david.hendry@MyDomain.com");
var group = GetGroup(adContext, "IT Solutions");

Console.ReadKey();
}
catch (AuthenticationException ex)
{
Console.ReadKey();
}
}
}
}

Advertisements

CRM Online – Retrieve all users

Being reasonably new to the CRM SDK I needed a method to retrieve all users from the system.  This was needed as I was doing a piece of work to replicate permissions between CRM business units and SharePoint.

Retrieving all users via a query expression turned out to be quite simple…

private static EntityCollection RetrieveAllUsers(IOrganizationService service)
        {
            QueryExpression query = new QueryExpression
            {
                EntityName = "systemuser",
                ColumnSet = new ColumnSet(true),
                Criteria =
                {
                    Conditions =
                    {
                        new ConditionExpression
                        {
                            AttributeName = "businessunitid",
                            Operator = ConditionOperator.NotNull
                        }
                    }
                }
            };
            return service.RetrieveMultiple(query);
        }

The EntityCollection returns a number of useful attributes, such as the users’ business unit, whether they have a valid licence, account status and so on.