Ask
Ask

Reputation: 3746

AWS Cognito Admin GetUser with associated groups

I am using aws cognito sdk with .net core 3.1 webapi. The issue is, I have to display users info as well as user groups. ListUserApi https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_ListUsers.html doesn't return users group information. According to the docs I have to call other api ListUserInGroups (https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_ListUsersInGroup.html) but as I need both information on single table. This call would be really expensive for me. Is there any other api which returns user's profile info as well as user group info. I tried to find one but couldn't Also one other question do aws cognito api provied sorting functionality? Like sort by name of email? I can only see filtering option but not sorting.

Upvotes: 2

Views: 525

Answers (1)

Hardik
Hardik

Reputation: 33

No, there is no API to get list of users with group they are associated with.

If you only want group names associated with that user you try this workaround ,this will reduce some api calls :

Get All Groups using - ListGroups

now for each group call ListUsersInGroup,so you know group assigned with that list

var listUsersInGroupRequest = new ListUsersInGroupRequest
{
    UserPoolId = UserPoolId,
    GroupName = groupName
};

ListUsersInGroupResponse response = (await provider.ListUsersInGroupAsync(listUsersInGroupRequest));

var groupList = response?.Users.Select(x => new UserDTO()
{
    FirstName = x.Attributes.SingleOrDefault(x => x.Name == "given_name")?.Value,
    SurName = x.Attributes.SingleOrDefault(x => x.Name == "family_name")?.Value,
    Email = x.Attributes.SingleOrDefault(x => x.Name == "email")?.Value,
    Sub = x.Attributes.SingleOrDefault(x => x.Name == "sub")?.Value,
    Groups = groupName,
    UserName = x.Username
});

now you have different list of users for each group, so you can concat all list and use GroupBy by sub/username and aggregate string groups

allConcatedUserDTO.GroupBy(row => row.Sub)
    .Select(x => new UserDTO()
    {
        Sub = x.Key,
        UserName = x.FirstOrDefault()?.UserName ?? string.Empty,
        Email = x.FirstOrDefault()?.Email ?? string.Empty,
        FirstName = x.FirstOrDefault()?.FirstName ?? string.Empty,
        SurName = x.FirstOrDefault()?.SurName ?? string.Empty,
        Groups = string.Join(",", x.Select(y => y.Groups))
    }).ToList();

And ListUsers and ListUsersInGroup does not provide sorting functionality, but when you provide filter attribute in ListUsers request, result will be sorted by attribute name provided for filtering in ascending order.

Upvotes: 2

Related Questions