Amplify-js: Amplify Auth and user's groups

Created on 31 Oct 2019  路  6Comments  路  Source: aws-amplify/amplify-js

* Which Category is your question related to? *
Authentication via Cognito

* What AWS Services are you utilizing? *
Cognito

* Provide additional details e.g. code snippets *
Create a new project with amplify and add auth. Be sure to select cognito as authentication method. Once deployed with amplify push go to the Cognito console, select the newly created user pool and create a user and a group. Now add the user to your group.

Back on your app, import amplify-js and do the ritual setup of framework of your choice.
How to retrieve the group a logged in user is in?

import { Auth } from 'aws-amplify';
...
const user =  await Auth.currentAuthenticatedUser();

does not contain such information

Thanks in advance!

Most helpful comment

You can find a user's cognito group in the user's jwt accessToken or simply the payload.

import { Auth } from 'aws-amplify';

const user =  await Auth.currentAuthenticatedUser();

// the array of groups that the user belongs to
user.signInUserSession.accessToken.payload["cognito:groups"]

All 6 comments

You can find a user's cognito group in the user's jwt accessToken or simply the payload.

import { Auth } from 'aws-amplify';

const user =  await Auth.currentAuthenticatedUser();

// the array of groups that the user belongs to
user.signInUserSession.accessToken.payload["cognito:groups"]

@SanvirDessai thank you very much. It works like a charm.
@kaustavghosh06 y'all at AWS need to make things easier to find! :wink:

In seeing the above callout, I am going to resolve this since you were able to resolve your issue.

During sign up I am trying to sign users up into different groups.
How can I do this in aws amplify?

Thank you!

@arhoy this can be done with a post confirmation trigger:

export function postConfirmationTrigger(event, context, callback) {
  const params = {
    GroupName: "BasicUsers",
    UserPoolId: event.userPoolId,
    Username: event.userName
  };

  CognitoIdentityServiceProvider.adminAddUserToGroup(params)
    .promise()
    .then(res => callback(null, event))
    .catch(err => callback(err, event));
}

Shouldn't this be documented somewhere?

Was this page helpful?
0 / 5 - 0 ratings