Question:
I have several Lambda functions behind an API Gateway that is using Lambda Proxy integration. Each function is configured with the AWS_IAM authorizer. I am able to successfully authenticate against a Cognito User Pool and then retrieve the user’s ID from the Lambda event like described here https://serverless-stack.com/chapters/mapping-cognito-identity-id-and-user-pool-id.html.
However I am struggling to get the list of User Pool groups that the authenticated user belongs to. Ideally they would be passed as part of the event since the Cognito authorizer would already have this info. I have seen mentions of adding mappings to the method’s Integration Request but that doesn’t seem to be an option when using Lambda Proxy integration.
I have also tried all the recommendations here with no luck. https://github.com/aws-amplify/amplify-js/issues/390
Answer:
I can’t believe they just don’t pass this in. Here’s what I did:
1. Modify the serverless.yaml
to get permissions:
1 2 3 4 5 |
- Effect: Allow Action: - cognito-idp:AdminListGroupsForUser Resource: ${self:custom.userPoolArn} |
That lets my lambda functions access the AdminListGroupsForUser function.
2. Get Cognito group in the lambda function
Use the string parsing function you referenced here you can get the UserPoolUserId and the UserPoolId. My lambda code is in python but its the same idea:
1 2 3 4 |
auth_provider = event['requestContext']['identity']['cognitoAuthenticationProvider'] userPoolUserId = parts[-1] # the last part of the list userPoolId = parts[0].split('/')[-1] |
Then with those values you pass to the AdminListGroupsForUser
that you gave permissions to in the previous step.
1 2 3 4 5 6 7 |
cognito = boto3.client('cognito-idp') groups = cognito.admin_list_groups_for_user( UserPoolId = userPoolId, Username = userPoolUserId ) print(groups) |
You’ll then get a hash with all the groups they belong to. If there are a bunch of groups you can pass other parameters to AdminListGroupsForUser
to get them. Hope that works for you!