In AWS Cognito, you can add a user to a group (after first creating a group). A user may belong to one or more groups.
With using the JavaScipt SDK (https://github.com/aws/amazon-cognito-identity-js), is there a way to read the assigned Groups? Would aws-sdk
provide access over amazon-cognito-identity-js
?
You do not need to decode anything, the data is already available from
session.getIdToken().payload['cognito:groups']
You can now easily get the user groups from the user session:
session.getIdToken().decodePayload();
This contains an array of groups in the
cognito:groups
key returnedI originally expected the Cognito JavaScript API to provide a simple property or method to return the list of groups, but instead I concluded that it was buried within a token, and thus had to learn about jwt. Once the Cognito User is established and the session is retrieved, the array of groups is available within the IdToken.
If you just need the Cognito UserPools Groups the Authenticated User is a member of, instead of making a separate API call, that data is encoded in the idToken.jwtToken that you received when authenticating.
This is useful for client-side rendering/access decisions in angular/react/etc. apps.
See the "cognito:groups" array claim in this example decoded idToken.jwtToken:
Hope this helps.
This API does exist - AdminListGroupsForUser. The reason you're not seeing it is, as the name implies, that the API is currently only available on an admin basis. Cognito doesn't include admin APIs in the mobile SDKs. It would be included in the AWS SDKs/server side SDKs, but it's worth noting that this API does require developer credentials, as do all admin APIs.
If you're using Amplify, if you use the currentAuthenticatedUser method you can get the groups from the response using:
Or using the currentSession method you can use either of:
or