Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get cognito id in a lambda function?

How can I get the the cognito id of the user initiating the action in a Lambda function ?

the lambda function is triggered on s3 upload by a cognito authenticated user.

if I look in : event.Records[0].userIdentity.principalId, all i get is a string saying "CognitoIdentityCredentials"

like image 859
WKx Avatar asked Oct 30 '25 15:10

WKx


1 Answers

As Vinay stated, we can't get the cognito id directly. Here is a workaround I implemented, if anyone is interested. It guarantees the authentication of your cognito user, but requires that you store files in a different directory per user:

  • get the user to upload there file to 'yourBucket/cognito-id/*'

  • set the cognito authenticated user's policy so they can't upload anywhere else :

"Resource": "arn:aws:s3:::yourBucket/${cognito-identity.amazonaws.com:sub}/"

  • In your lambda function, read the cognito id from the file key, for example :

id = event.Records[0].s3.object.key.split('/')[0]

like image 169
WKx Avatar answered Nov 01 '25 14:11

WKx



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!