In my Cognito userpool, I created a user group "Admins", attached an IAM Role and added my user to it.
This works all fine, but now I need to find out in my application code if the current user is in this group.
Is there any way to retrieve the groups from the CognitoUser object? I tried getUserAttributes but it doesn't seem to include the group.
User's groups are only visible through the Admin APIs (APIs using AWS account credentials). To see the groups for a user use AdminListGroupsForUser.
What's the use case to retrieve Group information in the application code?
In my current use case I want to enable some actions in the UI only to the users in the "Admin" group.
The other users don't have the IAM rights for said action anyway, so I don't want to show them the buttons.
Is there another way to distinguish users in one user group from the others without assigning them another custom attribute?
The groups information is available in the id token for the user which would fit your use case.
`if (cognitoUser != null) {
cognitoUser.getSession(function(err, session) {
if (err) {
alert(err);
return;
}
console.log('session validity: ' + session.isValid());
var sessionIdInfo = jwt_decode(session.getIdToken().jwtToken);
console.log("Group Info :"+sessionIdInfo['cognito:groups']);
});
}`
The value will be a comma separate string with all the user groups.
Be sure to include the jwt-decode.js & jwt-decode.min.js files
in case if somebody finds this issue via google later, you don't really need to decode id token yourself. this is already done in CognitoIdToken constructor, so you can read cognito:groups directly from session.getIdToken().payload. Would be nice to see this in typedefs though…
Most helpful comment
The value will be a comma separate string with all the user groups.
Be sure to include the jwt-decode.js & jwt-decode.min.js files