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

2

4

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?

Daudet answered 8/9, 2020 at 21:27 Comment(2)
You get two tokens back from cognito, you get an Idtoken and a Auth token. In the aws docs, you can see how one can validate the token, since you are using JS, a lot of npm packages will do this for you. I believe the IDtoken is the one that holds user info such as groups / tags. Using jwt.io you can read the contents of your tokens.Linstock
Hello @PHPNoob, I tried to get the IdToken also, but it returns information such as email, auth_time, nothing regarding the groups.Daudet
C
8

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"]
Cinderellacindi answered 9/9, 2020 at 3:21 Comment(1)
Super thanks Dylan, I tried several approaches but this one and your answer is exactly what I need, thank you again!Daudet
A
1

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"])
Arouse answered 13/4 at 18:12 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.