Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AWS Cognito, checking if authenticated user is in group or is admin using amplify

I'm trying to identify if the authenticated user is admin or not, by checking if it belongs to a specific group. I'm using amplify in my React application and tried several methods, such as Auth.currentUserInfo(), Auth.currentAuthenticatedUser() and also getting the jwt token to see if somehow it's returned in the token, but I didn't find any information regarding that. I saw some people saying that exists a payload cognito:groups in the token here, but that may be changed, because in my returned token it does not exists.

Another thing that I thought would work is the scope that comes in the jwt (aws.cognito.signin.user.admin), but it seems that every created user using amplify is returning this scope.

Is it possible to check if an authenticated user belongs to a group or if it's an admin user from cognito?

like image 766
Maturano Avatar asked Oct 22 '25 07:10

Maturano


2 Answers

You can get the user groups from the session. It is in user.signInUserSession.accessToken.payload["cognito:groups"] which will contain an array of all groups for the user.

Here is a short example:

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"]
like image 186
Dylan Avatar answered Oct 23 '25 21:10

Dylan


Auth.currentAuthenticatedUser() is deprecated in v6. Here is how I did it v6.

import { fetchAuthSession } from "aws-amplify/auth";

const { tokens } = await fetchAuthSession();
console.log("user belongs to following groups: " + tokens.accessToken.payload["cognito:groups"])
like image 31
Abdul Basith Avatar answered Oct 23 '25 23:10

Abdul Basith