AppSync: Get user information in $context when using AWS_IAM auth

后端 未结 5 1578
迷失自我
迷失自我 2020-12-24 15:47

In AppSync, when you use Cognito User Pools as your auth setting your identity you get

identity: 
   { sub: \'bcb5cd53-315a-40df-a41b-1db02a4c1bd9\',
     is         


        
5条回答
  •  北荒
    北荒 (楼主)
    2020-12-24 16:07

    Here is bad answer that works. I notice that cognitoIdentityAuthProvider: '"cognito-idp.us-west-2.amazonaws.com/us-west-2_HighBob","cognito-idp.us-west-2.amazonaws.com/us-west-2_HighBob:CognitoSignIn:1a072f08-5c61-4c89-807e-417d22702eb7" contains the Cognito user's sub (the big after CognitoSignIn). You can extract that with a regex and use the aws-sdk to get the user's info from cognito user pool.

    ///////RETRIEVE THE AUTHENTICATED USER'S INFORMATION//////////
    if(event.context.identity.cognitoIdentityAuthType === 'authenticated'){
        let cognitoidentityserviceprovider = new AWS.CognitoIdentityServiceProvider();
        //Extract the user's sub (ID) from one of the context indentity fields
        //the REGEX in match looks for the strings btwn 'CognitoSignIn:' and '"', which represents the user sub
        let userSub = event.context.identity.cognitoIdentityAuthProvider.match(/CognitoSignIn:(.*?)"/)[1];
        let filter = 'sub = \"'+userSub+'\"'    // string with format = 'sub = \"1a072f08-5c61-4c89-807e-417d22702eb7\"'
        let usersData = await cognitoidentityserviceprovider.listUsers( {Filter:  filter, UserPoolId: "us-west-2_KsyTKrQ2M",Limit: 1}).promise()
        event.context.identity.user=usersData.Users[0]; 
    

    }

    It's a bad answer because you are pinging the User Pool database instead of just decoding a JWT.

提交回复
热议问题