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
I can't believe they just don't pass this in. Here's what I did:
serverless.yaml
to get permissions: - Effect: Allow
Action:
- cognito-idp:AdminListGroupsForUser
Resource: ${self:custom.userPoolArn}
That lets my lambda functions access the AdminListGroupsForUser 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:
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.
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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With