/// <summary> /// Gets the groups for which a given user is a member of /// </summary> /// <param name="userId">The Id of the User to check</param> /// <returns>A Task of ApplicationGroup items</returns> public async Task <List <ApplicationGroup> > GetGroupMembershipForUser(string userId) { List <ApplicationGroup> items = new List <ApplicationGroup>(); var graphClient = GetAuthenticatedClient(userId); // Get groups the current user is a direct member of. IUserMemberOfCollectionWithReferencesPage memberOfGroups = await graphClient.Me.MemberOf.Request().GetAsync(); if (memberOfGroups?.Count > 0) { foreach (var directoryObject in memberOfGroups) { // We only want groups, so ignore DirectoryRole objects. if (directoryObject is Group) { Group group = directoryObject as Group; items.Add(new ApplicationGroup { DisplayName = group.DisplayName, AzureAdObjectIdentifier = group.Id }); } } } return(items); }
// Get the groups that the current user is a direct member of. // This snippet requires an admin work account. public async Task <List <ResultsItem> > GetMyMemberOfGroups(GraphServiceClient graphClient) { List <ResultsItem> items = new List <ResultsItem>(); // Get groups the current user is a direct member of. IUserMemberOfCollectionWithReferencesPage memberOfGroups = await graphClient.Me.MemberOf.Request().GetAsync(); if (memberOfGroups?.Count > 0) { foreach (var directoryObject in memberOfGroups) { // We only want groups, so ignore DirectoryRole objects. if (directoryObject is Group) { Group group = directoryObject as Group; items.Add(new ResultsItem { Display = group.DisplayName, Id = group.Id }); } } } return(items); }
public static async Task <IActionResult> Run( [HttpTrigger(AuthorizationLevel.Anonymous, "get", Route = "groups")] HttpRequest req, ILogger log) { var groups = new List <string>(); try { string userObjectId = req.Query["userObjectId"]; GraphServiceClient graphClient = GetGraphClient(); IUserMemberOfCollectionWithReferencesPage result = await graphClient.Users[userObjectId].MemberOf.Request().GetAsync(); foreach (Group group in result) { groups.Add(group.DisplayName); } } catch (Exception e) { log.LogError(e.Message); } var commaseparatedGroups = string.Join(",", groups); return(new JsonResult(new { commaseparatedGroups })); }
public async Task <IEnumerable <GroupInfo> > GetAllGroupsOfUser(string mail) { IList <GroupInfo> result = new List <GroupInfo>(); IUserMemberOfCollectionWithReferencesPage memberOfGroups = await _graphServiceClient.Users[mail].MemberOf.Request().GetAsync(); //var transitiveMemberOf = await _graphServiceClient.Users[mail].TransitiveMemberOf.Request().GetAsync(); do { foreach (var directoryObject in memberOfGroups) { // We only want groups, so ignore DirectoryRole objects. if (directoryObject is Group) { Group group = directoryObject as Group; result.Add(new GroupInfo { Id = group.Id, DisplayName = group.DisplayName }); } } }while (memberOfGroups.NextPageRequest != null && (memberOfGroups = await memberOfGroups.NextPageRequest.GetAsync()).Count > 0); return(result); }
public async Task <ICollection <string> > GetUserGroupIds() { GraphServiceClient client = new GraphServiceClient(_authProvider); IUserMemberOfCollectionWithReferencesPage MemberReferences = await client.Me.MemberOf.Request().WithUserAssertion(GetUserAssertion()).GetAsync(); ICollection <string> GroupList = MemberReferences.CurrentPage.Where(g => g.ODataType == "#microsoft.graph.group") .Select(g => g.Id) .ToList(); return(GroupList); }
/// <summary> /// Gets the signed-in user groups and roles. A more efficient implementation that gets both group and role membership in one call /// </summary> /// <param name="accessToken">The access token for MS Graph.</param> /// <returns> /// A list of UserGroupsAndDirectoryRoles /// </returns> public async Task <UserGroupsAndDirectoryRoles> GetCurrentUserGroupsAndRolesAsync(string accessToken) { UserGroupsAndDirectoryRoles userGroupsAndDirectoryRoles = new UserGroupsAndDirectoryRoles(); IUserMemberOfCollectionWithReferencesPage memberOfDirectoryRoles = null; try { PrepareAuthenticatedClient(accessToken); memberOfDirectoryRoles = await graphServiceClient.Me.MemberOf.Request().GetAsync(); if (memberOfDirectoryRoles != null) { do { foreach (var directoryObject in memberOfDirectoryRoles.CurrentPage) { if (directoryObject is Group) { Group group = directoryObject as Group; // Trace.WriteLine($"Got group: {group.Id}- '{group.DisplayName}'"); userGroupsAndDirectoryRoles.Groups.Add(group); } else if (directoryObject is DirectoryRole) { DirectoryRole role = directoryObject as DirectoryRole; // Trace.WriteLine($"Got DirectoryRole: {role.Id}- '{role.DisplayName}'"); userGroupsAndDirectoryRoles.DirectoryRoles.Add(role); } } if (memberOfDirectoryRoles.NextPageRequest != null) { userGroupsAndDirectoryRoles.HasOverageClaim = true; //check if this matches 150 per token limit memberOfDirectoryRoles = await memberOfDirectoryRoles.NextPageRequest.GetAsync(); } else { memberOfDirectoryRoles = null; } } while (memberOfDirectoryRoles != null); } return(userGroupsAndDirectoryRoles); } catch (ServiceException e) { Trace.Fail("We could not get user groups and roles: " + e.Error.Message); return(null); } }
public async Task <IList <Group> > GetMyGroupsAsync(string accessToken) { IList <Group> groups = new List <Group>(); try { // Get groups the current user is a direct member of. IUserMemberOfCollectionWithReferencesPage memberOfGroups = await _serviceClient.Me.MemberOf.Request().GetAsync(); if (memberOfGroups?.Count > 0) { foreach (var directoryObject in memberOfGroups) { // We only want groups, so ignore DirectoryRole objects. if (directoryObject is Group) { Group group = directoryObject as Group; groups.Add(group); } } } // If paginating while (memberOfGroups.NextPageRequest != null) { memberOfGroups = await memberOfGroups.NextPageRequest.GetAsync(); if (memberOfGroups?.Count > 0) { foreach (var directoryObject in memberOfGroups) { // We only want groups, so ignore DirectoryRole objects. if (directoryObject is Group) { Group group = directoryObject as Group; groups.Add(group); } } } } } catch (Exception) { throw; } return(groups); }
/// <summary>Gets the groups the signed-in user's is a member of.</summary> /// <param name="accessToken">The access token for MS Graph.</param> /// <returns>A list of Groups</returns> public async Task <IList <Group> > GetCurrentUsersGroupsAsync(string accessToken) { IUserMemberOfCollectionWithReferencesPage memberOfGroups = null; IList <Group> groups = new List <Group>(); try { PrepareAuthenticatedClient(accessToken); memberOfGroups = await graphServiceClient.Me.MemberOf.Request().GetAsync(); if (memberOfGroups != null) { do { foreach (var directoryObject in memberOfGroups.CurrentPage) { if (directoryObject is Group) { Group group = directoryObject as Group; // Trace.WriteLine("Got group: " + group.Id); groups.Add(group as Group); } } if (memberOfGroups.NextPageRequest != null) { memberOfGroups = await memberOfGroups.NextPageRequest.GetAsync(); } else { memberOfGroups = null; } } while (memberOfGroups != null); } return(groups); } catch (ServiceException e) { Trace.Fail("We could not get user groups: " + e.Error.Message); return(null); } }
/// <summary> /// Gets the current user directory roles. /// </summary> /// <param name="accessToken">The access token for MS Graph.</param> /// <returns> /// A list of directory roles /// </returns> public async Task <IList <DirectoryRole> > GetCurrentUserDirectoryRolesAsync(string accessToken) { IUserMemberOfCollectionWithReferencesPage memberOfDirectoryRoles = null; IList <DirectoryRole> DirectoryRoles = new List <DirectoryRole>(); try { PrepareAuthenticatedClient(accessToken); memberOfDirectoryRoles = await graphServiceClient.Me.MemberOf.Request().GetAsync(); if (memberOfDirectoryRoles != null) { do { foreach (var directoryObject in memberOfDirectoryRoles.CurrentPage) { if (directoryObject is DirectoryRole) { DirectoryRole DirectoryRole = directoryObject as DirectoryRole; // Trace.WriteLine("Got DirectoryRole: " + DirectoryRole.Id); DirectoryRoles.Add(DirectoryRole as DirectoryRole); } } if (memberOfDirectoryRoles.NextPageRequest != null) { memberOfDirectoryRoles = await memberOfDirectoryRoles.NextPageRequest.GetAsync(); } else { memberOfDirectoryRoles = null; } } while (memberOfDirectoryRoles != null); } return(DirectoryRoles); } catch (ServiceException e) { Trace.Fail("We could not get user DirectoryRoles: " + e.Error.Message); return(null); } }
/// <summary> /// Returns all the groups that the user is a direct member of. /// </summary> /// <param name="membersCollectionPage">First page having collection of directory roles and groups</param> /// <returns>List of groups</returns> private static List <Group> ProcessIGraphServiceMemberOfCollectionPage(IUserMemberOfCollectionWithReferencesPage membersCollectionPage) { List <Group> allGroups = new List <Group>(); try { if (membersCollectionPage != null) { do { // Page through results foreach (DirectoryObject directoryObject in membersCollectionPage.CurrentPage) { //Collection contains directory roles and groups of the user. //Checks and adds groups only to the list. if (directoryObject is Group) { allGroups.Add(directoryObject as Group); } } // are there more pages (Has a @odata.nextLink ?) if (membersCollectionPage.NextPageRequest != null) { membersCollectionPage = membersCollectionPage.NextPageRequest.GetAsync().Result; } else { membersCollectionPage = null; } } while (membersCollectionPage != null); } } catch (ServiceException ex) { Console.WriteLine($"We could not process the groups list: {ex}"); return(null); } return(allGroups); }
// Gets the groups that the signed-in user is a member of. // This snippet requires an admin work account. public static async Task <IUserMemberOfCollectionWithReferencesPage> GetCurrentUserGroupsAsync() { IUserMemberOfCollectionWithReferencesPage memberOfGroups = null; try { var graphClient = AuthenticationHelper.GetAuthenticatedClient(); memberOfGroups = await graphClient.Me.MemberOf.Request().GetAsync(); foreach (var group in memberOfGroups) { Debug.WriteLine("Got group: " + group.Id); } return(memberOfGroups); } catch (ServiceException e) { Debug.WriteLine("We could not get user groups: " + e.Error.Message); return(null); } }
public IEnumerable <List <DirectoryObject> > GetMemberOf(User user, CancellationToken token) { IUserMemberOfCollectionWithReferencesPage page = null; try { page = client.Users[user.Id].MemberOf.Request().GetAsync(token).Result; } catch (Exception ex) { HandleException(ex, null, messageOnlyExceptions, $"Get member of for user: {user.DisplayName}"); } while (page != null) { yield return(page.ToList()); if (page.NextPageRequest == null) { break; } page = page.NextPageRequest.GetAsync(token).Result; } }
//Returns a list of groups that the given user belongs to public async Task <List <ResultsItem> > UserMemberOf(string alias) { User user = FindByAlias(alias).Result; List <ResultsItem> items = new List <ResultsItem>(); IUserMemberOfCollectionWithReferencesPage groupsCollection = await _graphClient.Users[user.Id].MemberOf.Request().GetAsync(); if (groupsCollection?.Count > 0) { foreach (DirectoryObject dirObject in groupsCollection) { if (dirObject is Group) { Group group = dirObject as Group; items.Add(new ResultsItem { Display = group.DisplayName, Id = group.Id }); } } } return(items); }
public static void AppModeRequests() { try { //********************************************************************* // setup Microsoft Graph Client for app-only. //********************************************************************* if (Constants.ClientIdForAppAuthn != "ENTER_YOUR_APP_ONLY_CLIENT_ID" && Constants.Tenant != "ENTER_YOUR_TENANT_NAME" && Constants.ClientSecret != "ENTER_YOUR_CLIENT_SECRET") { client = AuthenticationHelper.GetAuthenticatedClientForApp(); } else { Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine("You haven't configured a value for ClientIdForAppAuthn, Tenant, and/or ClientSecret in Constants.cs. Please follow the Readme instructions for configuring this application."); Console.ResetColor(); Console.ReadKey(); return; } } catch (Exception ex) { Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine("Acquiring a token failed with the following error: {0}", ex.Message); if (ex.InnerException != null) { //You should implement retry and back-off logic per the guidance given here:http://msdn.microsoft.com/en-us/library/dn168916.aspx //InnerException Message will contain the HTTP error status codes mentioned in the link above Console.WriteLine("Error detail: {0}", ex.InnerException.Message); } Console.ResetColor(); Console.ReadKey(); return; } Console.WriteLine("\nStarting app-mode requests..."); Console.WriteLine("\n=============================\n\n"); // Get first page of users in a tenant try { IGraphServiceUsersCollectionPage users = client.Users.Request().GetAsync().Result; foreach (User user in users) { Console.WriteLine("Found user: "******"\nError getting users {0} {1}", e.Message, e.InnerException != null ? e.InnerException.Message : ""); } // Get messages for a specific user (demonstrates $select operation) try { Console.WriteLine("\nEnter the email address of the user mailbox you want to retrieve:"); String email = Console.ReadLine(); List <Message> messages = client.Users[email].Messages.Request().Select("subject, receivedDateTime").GetAsync().Result.Take(3).ToList(); if (messages.Count == 0) { Console.WriteLine(" no messages in mailbox"); } foreach (Message message in messages) { Console.WriteLine(" Message: {0} received {1} ", message.Subject, message.ReceivedDateTime); } } catch (Exception e) { Console.WriteLine("\nError getting messages {0} {1}", e.Message, e.InnerException != null ? e.InnerException.Message : ""); } // Get groups for a specific user try { Console.WriteLine("\nEnter the email address of the user whose groups you want to retrieve:"); String email = Console.ReadLine(); IUserMemberOfCollectionWithReferencesPage userGroups = client.Users[email].MemberOf.Request().GetAsync().Result; if (userGroups.Count == 0) { Console.WriteLine(" user is not a member of any groups"); } foreach (DirectoryObject group in userGroups) { if (group is Group) { Group _group = group as Group; Console.WriteLine(" Id: {0} UPN: {1}", _group.Id, _group.DisplayName); } } } catch (Exception e) { Console.WriteLine("\nError getting group memberships {0} {1}", e.Message, e.InnerException != null ? e.InnerException.Message : ""); } //********************************************************************* // People picker // Search for a user using text string and match against userPrincipalName, displayName, giveName, surname //********************************************************************* Console.WriteLine("\nSearch for user (enter search string):"); String searchString = Console.ReadLine(); IGraphServiceUsersCollectionPage userCollection = null; try { string startsWithFilter = "startswith(displayName%2C+ '" + searchString + "')+or+startswith(userPrincipalName%2C+ '" + searchString + "')+or+startswith(givenName%2C+ '" + searchString + "')+or+startswith(surname%2C+ '" + searchString + "')"; userCollection = client.Users.Request().Filter(startsWithFilter).GetAsync().Result; } catch (Exception e) { Console.WriteLine("\nError getting User {0} {1}", e.Message, e.InnerException != null ? e.InnerException.Message : ""); } if (userCollection != null && userCollection.Count > 0) { foreach (User u in userCollection) { Console.WriteLine("User: DisplayName: {0} UPN: {1}", u.DisplayName, u.UserPrincipalName); } } else { Console.WriteLine("User not found"); } // Create a unified group Console.WriteLine("\nDo you want to create a new unified group? Click y/n\n"); ConsoleKeyInfo key = Console.ReadKey(); // We need two Group variables: one to pass to the AddAsync and another that stores the // created group returned by AddAsync(). The createdGroup variable will have a value for the Id // property. We'll need to use that value later. Group uGroup = null; Group createdGroup = null; if (key.KeyChar == 'y') { string suffix = GetRandomString(5); uGroup = new Group { GroupTypes = new List <string> { "Unified" }, DisplayName = "Unified group " + suffix, Description = "Group " + suffix + " is the best ever", MailNickname = "Group" + suffix, MailEnabled = true, SecurityEnabled = false }; try { createdGroup = client.Groups.Request().AddAsync(uGroup).Result; Console.WriteLine("\nCreated unified group {0}", createdGroup.DisplayName); } catch (Exception) { Console.WriteLine("\nIssue creating the group {0}", uGroup.DisplayName); uGroup = null; } } // Add group members. If the user has chosen to create a group, use that one. // If the user has chosen not to create a group, find one in the tenant. Group groupToAddMembers = new Group(); if (createdGroup != null) { groupToAddMembers = createdGroup; } else { string unifiedFilter = "groupTypes/any(gt:gt+eq+'Unified')"; List <Group> unifiedGroups = client.Groups.Request().Filter(unifiedFilter).GetAsync().Result.Take(5).ToList(); if (unifiedGroups != null && unifiedGroups.Count > 0) { groupToAddMembers = unifiedGroups.First(); } } // Get a set of users to add List <User> members = client.Users.Request().GetAsync().Result.Take(3).ToList(); if (groupToAddMembers != null) { //Add users foreach (User user in members) { try { client.Groups[groupToAddMembers.Id].Members.References.Request().AddAsync(user); Console.WriteLine("\nAdding {0} to group {1}", user.UserPrincipalName, groupToAddMembers.DisplayName); } catch (Exception e) { Console.WriteLine("\nError assigning member to group. {0} {1}", e.Message, e.InnerException != null ? e.InnerException.Message : ""); } } // Now remove the added users foreach (User user in members) { try { client.Groups[groupToAddMembers.Id].Members[user.Id].Reference.Request().DeleteAsync(); Console.WriteLine("\nRemoved {0} from group {1}", user.UserPrincipalName, groupToAddMembers.DisplayName); } catch (Exception e) { Console.WriteLine("\nError removing member from group. {0} {1}", e.Message, e.InnerException != null ? e.InnerException.Message : ""); } } } else { Console.WriteLine("\nCan't find any unified groups to add members to.\n"); } // If we created a group, remove it. if (createdGroup != null) { try { client.Groups[createdGroup.Id].Request().DeleteAsync().Wait(); Console.WriteLine("\nDeleted group {0}", createdGroup.DisplayName); } catch (Exception e) { Console.Write("Couldn't delete group. Error detail: {0}", e.InnerException.Message); } } // Get first five groups. try { List <Group> groups = client.Groups.Request().GetAsync().Result.Take(5).ToList(); foreach (Group group in groups) { Console.WriteLine(" Group Id: {0} upn: {1}", group.Id, group.DisplayName); foreach (string type in group.GroupTypes) { if (type == "Unified") { Console.WriteLine(": This is a Unifed Group"); } } } } catch (Exception e) { Console.Write("Couldn't get groups. Error detail: {0}", e.InnerException.Message); } }
// GET api/groups public async Task <List <Dictionary <string, string> > > Get() { // Sprinkle some ADAL logging, to taste. // Check out the AdalLoggerCallback implementation in Startup.cs LoggerCallbackHandler.Callback = new Startup.AdalLoggerCallback(); string authority = $"https://login.microsoftonline.com/{ConfigurationManager.AppSettings["ida:Tenant"]}"; AuthenticationContext context = new AuthenticationContext(authority); ClientCredential clientCredential = new ClientCredential( ConfigurationManager.AppSettings["ida:ClientId"], ConfigurationManager.AppSettings["ida:Password"]); AuthenticationResult result = await context.AcquireTokenAsync("https://graph.microsoft.com", clientCredential); string bearerToken = result.AccessToken; // Call Microsoft Graph API to get group membership for current user // What's with that Delegate? see this - https://github.com/microsoftgraph/msgraph-sdk-dotnet#2-authenticate-for-the-microsoft-graph-service GraphServiceClient graphClient = new GraphServiceClient( new DelegateAuthenticationProvider( (requestMessage) => { requestMessage.Headers.Authorization = new AuthenticationHeaderValue("Bearer", bearerToken); return(Task.FromResult(0)); })); var itemsList = new List <Dictionary <string, string> >(); // You can use odata filters with .Filter(filterString), like this: // // string f = "id eq 'a9bc2fe5-e997-4713-bb0c-2682f4f779c7'"; // var groups = await graphClient.Groups.Request().Filter(f).GetAsync(); string upn = ClaimsPrincipal.Current.Identity.Name; IUserMemberOfCollectionWithReferencesPage groups = await graphClient .Users[upn] .MemberOf .Request() .GetAsync(); if (groups?.Count > 0) { foreach (var directoryObject in groups) { // We only want groups, so ignore DirectoryRole objects if (directoryObject is Group) { Group group = directoryObject as Group; if (group.SecurityEnabled ?? false) { Dictionary <string, string> dict = new Dictionary <string, string>() { { "Description", group.Description }, { "DisplayName", group.DisplayName }, { "Id", group.Id } }; itemsList.Add(dict); } } } } return(itemsList); }