AWS Cognito - How To Get User's Group From Token Object
Asked Answered
P

4

19

I can see the user's assigned User Pool group in the returned user data object in the console after logging in. Everything I've tried to assign the group to a variable has failed. What am I missing? I can easily get the client_id, JWT's, and attributes.

The object path:

let userGroup = user.signInUserSession.accessToken.payload.cognito.groups[0];

However, this works:

user.signInUserSession.accessToken.payload.client_id;

This section of the object looks like this. I can retrieve the token, the user name, almost anything but groups.

signInUserSession: CognitoUserSession
    accessToken: CognitoAccessToken
        jwtToken: ...
        payload:
            auth_time: 1539824552
            client_id: "5u7o1o1...."
            cognito:groups: Array(1)
                0: "admin-full"
                length: 1
        ... more properties here...
        token_use: "access"
        username: "me"

I'm using Angular 6 and AWS-Amplify but I doubt that matters. Part of my code:

constructor(
    private amplifyService: AmplifyService,
  ) {}

this.amplifyService.auth().currentAuthenticatedUser()
      .then(user => {
         console.log('user data in checkLogin: ', user); // The whole object.
         console.log('user token in checkLogin: ', user.signInUserSession.accessToken.jwtToken); // Retrieves the token.

My whole session object for clarification:

CognitoUser {username: "me", pool: CognitoUserPool, Session: null, client: Client, signInUserSession: CognitoUserSession, …}
Session: null
attributes: {phone_number: "########", locale: "Silicon Valley", given_name: "J", family_name: "Preston", email: "[email protected]"}
authenticationFlowType: "USER_SRP_AUTH"
client: Client {endpoint: "https://cognito-idp.us-west-2.amazonaws.com/", userAgent: "aws-amplify/0.1.x js"}
pool: CognitoUserPool {userPoolId: "us-west-2_UW9KsJm0o", clientId: "5u7o1o1v288e...", client: Client, advancedSecurityDataCollectionFlag: true, storage: Storage}
preferredMFA: "NOMFA"
signInUserSession: CognitoUserSession
accessToken: CognitoAccessToken
jwtToken: "eyJraWQiOiJwaUdRSnc..."
payload:
auth_time: 1539881072
client_id: "5u7o1o1v2..."
cognito:groups: ["admin"]
event_id: "168d9cc3-d2f5-11e8-ae71-f734087f965a"
exp: 1539884672
iat: 1539881072
iss: "https://cognito-idp.us-west-2.amazonaws.com/us-west-2_UW9KsJm0o"
jti: "13c4c552-ee70-4f8a-b64d-f95e0bdc81cf"
scope: "aws.cognito.signin.user.admin openid"
sub: "96a047b2-ae9a-42ff-af09-fc1c0802b88f"
token_use: "access"
username: "me"
version: 2
__proto__: Object
__proto__: CognitoJwtToken
clockDrift: 0
idToken: CognitoIdToken {jwtToken: "eyJraWQiOiI...", payload: {…}}
refreshToken: CognitoRefreshToken {token: ""}
__proto__: Object
storage: Storage {CognitoIdentityServiceProvider.5u7o1o1....LastAuthUser: "me", CognitoIdentityServiceProvider.5u7o1o1v....jimadmin.accessToken: "eyJraWQiOiJ...", CognitoIdentityServiceProvider.5u7o1o1....jimadmin.idToken: "eyJraWQiOiI3...", CognitoIdentityServiceProvider.5u7o1o1....jimadmin.refreshToken: "", CognitoIdentityServiceProvider.5u7o1o1....jimadmin.tokenScopesString: "email openid aws.cognito.signin.user.admin", …}
username: "me"
Pomfret answered 18/10, 2018 at 16:2 Comment(0)
H
25

The group is in the session Object and in the idToken Payload as seen below.
The group is not there if your user is not in a group. You should be able to access it like accessToken.payload['cognito:groups'];

I happen to have a cognito session object handy for a user in a group, which shows all tokens and all their payloads. As well as what you get when you get the user attributes.

session:

{
   "idToken":{
      "jwtToken":"eyJraWQiOiJQS1wvMHNNMlk...",
      "payload":{
         "sub":"ceb234234-b0e0-4c3d-8abc-af08c002b4de",
         "cognito:groups":[
            "user"
         ],
         "email_verified":true,
         "iss":"https://cognito-idp.us-east-2.amazonaws.com/us-east-2_sinJIhGA8",
         "phone_number_verified":false,
         "cognito:username":"ceba8336-b0e0-4c3d-8abc-af08c002b4de",
         "aud":"203e1rl2o1d8d5chhs9v6s1i79",
         "event_id":"89502ffe-d2fe-11e8-8427-1b3482253d90",
         "token_use":"id",
         "auth_time":1539885130,
         "exp":1539888730,
         "iat":1539885130,
         "email":"[email protected]"
      }
   },
   "refreshToken":{
      "token":"eyJjdHkiOiJKV1QiLCJlb..."
   },
   "accessToken":{
      "jwtToken":"eyJraWQiOiI4N2pRRnpqSm..",
      "payload":{
         "sub":"ceba8336-b0e0-4c3d-8abc-af08c002b4de",
         "device_key":"us-east-2_94234234234b-4cec-ae49-b1f90555d979",
         "cognito:groups":[
            "user"
         ],
         "iss":"https://cognito-idp.us-east-2.amazonaws.com/us-east-2_sinJIhGA8",
         "client_id":"203e1rl223423hhs9v6s1i79",
         "event_id":"895234fe-d2fe-11e8-8427-1b3482253d90",
         "token_use":"access",
         "scope":"aws.cognito.signin.user.admin",
         "auth_time":1539885130,
         "exp":1539888730,
         "iat":1539885130,
         "jti":"936fd8f9-c091-4f642345f-ba9454f16b9c",
         "username":"ceba83362342-4c3d-8abc-af08c002b4de"
      }
   },
   "clockDrift":0
}

userAttributes:

{  
   "details":[  
      {  
         "Name":"sub",
         "Value":"ceba8336-4234-4c3d-8abc-af08c002b4de"
      },
      {  
         "Name":"email_verified",
         "Value":"true"
      },
      {  
         "Name":"phone_number_verified",
         "Value":"false"
      },
      {  
         "Name":"email",
         "Value":"[email protected]"
      }
   ]
}
Homburg answered 18/10, 2018 at 16:25 Comment(7)
The assigned group is in the object returned by Cognito. I can see it there along with all the other data and JWT's. Since it lives there I want to use it to determine which parts of the application the user can visit. I'll build out the returned object a bit more with an edit to make this clear.Pomfret
Adding more to my answer.Homburg
I have mostly the same properties in my console but I also have cognito:groups. That is what I'm showing above. I have no idea why you aren't getting the groups included. I'll edit and add some of my code for clarity.Pomfret
The answer is: this.userGroup = user.signInUserSession.accessToken.payload['cognito:groups']; The var holds an array with my user group/s. Thanks! I tried [] before but not the ' '. They made the difference.Pomfret
I have edited my answer. It was my fault, the user I was testing with wasn't associated with a group..Homburg
Well, we put everything for this issue out there so hopefully it will help others. :-)Pomfret
I have no idea why my session property value is null?Hinge
P
20

If someone is using Amplify


Auth.currentAuthenticatedUser()
.then(data => console.log(data.signInUserSession.accessToken.payload['cognito:groups']));

Phosphine answered 5/6, 2021 at 5:26 Comment(0)
N
2

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"])

https://mcmap.net/q/665650/-aws-cognito-checking-if-authenticated-user-is-in-group-or-is-admin-using-amplify

Nomadic answered 16/4 at 22:47 Comment(2)
Please add the code here as well (but preserve the link too for reference). The reason is simple: if the linked question is deleted, then your answer here won't help anyone.Rudiger
@Rudiger Thank you very much for the suggestion. Have updated the answer with code.Nomadic
P
0
public signIn(user: IUser): Promise<any> {
    return Auth.signIn(user.email, user.password)
    .then((data) => {    console.log(data.signInUserSession.accessToken.payload['cognito:groups'][0]);
        this.authenticationSubject.next(true);
    }).catch((e)=>{
 throw e;
    });
  }
Pax answered 3/5, 2023 at 14:13 Comment(1)
As it’s currently written, your answer is unclear. Please edit to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers in the help center.Yoshieyoshiko

© 2022 - 2024 — McMap. All rights reserved.