Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add custom roles or groups added in Cognito JWT token?

I'm really struggling to add custom roles or groups in the JWT token generated by Cognito. I'm using the Pre-Token generation trigger in Cognito to execute a Lambda. I'm adding the "groupOverrideDetails" object in the response. Here is my final output:

"response": {
        "claimsOverrideDetails": {
            "claimsToAddOrOverride": {
                "custom_attribute_key2": "attribute_value2",
                "custom_attribute_key": "attribute_value"
            }
        },
        "groupOverrideDetails": {
            "groupsToOverride": [
                "developers"
            ],
            "iamRolesToOverride": [
                "S3_Access_Admin"
            ],
            "preferredRole": "S3_Access_Admin"
        }
    }

But in my JWT token, I do not see any above mentioned roles or groups.

  1. Can you please tell me what am I missing?
    1. Secondly, is it important to have "developers" group and "S3_Access_Admin" role to actually exist in AWS? What if I need to add a custom group in AWS?
like image 247
Shiva Wahi Avatar asked Nov 26 '25 04:11

Shiva Wahi


1 Answers

I don't know what validation is done on the groups and roles you add in the claim, but the only thing I see is that you need to nest the groupOverrideDetails inside the claimsOverrideDetails. Here is a snippet I was able to get working.

    role_arns = ...
    event['response'] = {
        'claimsOverrideDetails': {
            'groupOverrideDetails': {
                # we don't need to modify the groups in our case
                'groupsToOverride': request['groupConfiguration']['groupsToOverride'],
                # this will set the claim 'cognito:roles'
                'iamRolesToOverride': role_arns,
                # this will set the claim 'cognito:preferredRole'
                'preferredRole': role_arns[0],
            },
    }
    return event

The following stackoverflow question helped me: AWS Cognito - create groups from ADFS as Cognito Groups

For future reference, here is the aws doc. Scroll down to the section titled Pre Token Generation Example: Modify the User's Group Membership https://docs.aws.amazon.com/cognito/latest/developerguide/user-pool-lambda-pre-token-generation.html

like image 67
Justin Thomas Avatar answered Nov 28 '25 15:11

Justin Thomas