UserPool.getCurrentUser()返回null [后端]

时间:2019-01-05 07:18:28

标签: node.js amazon-cognito

正在尝试建立联盟身份以获取身份凭证。但是,当我尝试执行 getCurrentUser()时,响应为null。与此相关的另一件事是,正在后端上尝试此操作。那么它将在后端工作吗?以及为什么在尝试getCurrentUser时得到空响应?有想法吗?

var data = {
    UserPoolId: userPoolId,
    ClientId: appClientId,
  };

var userPool = new AmazonCognitoIdentity.CognitoUserPool(data);
console.log(userPool);
var cognitoUser = userPool.getCurrentUser();
console.log(cognitoUser);

userPool 的日志响应为

CognitoUserPool {
    userPoolId: 'us-east-6_hxxxx2U',
    clientId: '`6heh4h8h848h4884h05',
    client:
     Client {
       endpoint: 'https://cognito-idp.us-east-1.amazonaws.com/',
       userAgent: 'aws-amplify/0.1.x js' },
    advancedSecurityDataCollectionFlag: true,
    storage:
     { [Function: MemoryStorage]
       setItem: [Function: setItem],
       getItem: [Function: getItem],
       removeItem: [Function: removeItem],
       clear: [Function: clear] } }

cognitoUser的日志响应为NULL

那么为什么要给出正确的值作为输入,但响应为null?

2 个答案:

答案 0 :(得分:1)

潜在原因很少:

  1. 使用getCurrentUser()代替getCurrentUser(Data)
  2. 如果您未在后端登录用户,则无法获得当前用户。如果用户在前端登录,则可以使用一个函数将用户的id_token发送到后端,并使用它在后端登录。

关于第二点:

id_token包含一个称为有效负载的部分,其中包含用户的用户名和其他属性。有关详细信息:https://docs.aws.amazon.com/cognito/latest/developerguide/amazon-cognito-user-pools-using-tokens-with-identity-providers.html#amazon-cognito-user-pools-using-the-id-token

使用id_token时,应先验证签名,然后再允许用户采取进一步行动。可以在https://github.com/awslabs/aws-support-tools/tree/master/Cognito/decode-verify-jwt中找到用于验证的代码 您可以在此处添加操作代码:

                    .....
                    // and the Audience (use claims.client_id if verifying an access token)

                    if (claims.aud != app_client_id) {

                        callback('Token was not issued for this audience');

                    }

                    //add your code here

                    callback(null, claims);

                }).

                catch(function() {

                    callback('Signature verification failed');

                });

用户信息应位于claims中。

答案 1 :(得分:0)

这是因为我在这里发布的代码是用于前端的。 https://docs.aws.amazon.com/cognito/latest/developerguide/amazon-cognito-user-pools-authentication-flow.html上有一篇文章清楚地说明了我们应该如何尝试对用户进行身份验证。

因此,在正确的身份验证流程之后,我们将使用cognitoidentity.getCredentialsForIdentity() [请参考官方sdk文档]

传递所需的数据。