DEV Community

loading...
Cover image for Check if a user is part of a Cognito group in AWS Amplify

Check if a user is part of a Cognito group in AWS Amplify

Beez Fedia
I'm interested in Tech4Good, web and mobile development, and accessible design.
・1 min read

If you're looking to understand if an authenticated user is in a specific group the following method may help:

import { Auth } from 'aws-amplify';

const user =  await Auth.currentAuthenticatedUser();

// Returns an array of groups
const groups = user.signInUserSession.accessToken.payload["cognito:groups"];
Enter fullscreen mode Exit fullscreen mode

user.signInUserSession.accessToken.payload["cognito:groups"] returns an array of all the groups the user belongs to.

To discover if a user is part of the admin group use the array includes method:

const groups = user.signInUserSession.accessToken.payload["cognito:groups"];

groups.includes('admin'); // true
Enter fullscreen mode Exit fullscreen mode

For IE and older browsers use indexOf:

const groups = user.signInUserSession.accessToken.payload["cognito:groups"];

groups.indexOf('admin') !== -1; // true
Enter fullscreen mode Exit fullscreen mode

Happy days!

Discussion (0)