【问题标题】:AWS - nodejs SDK - CognitoIdentityServiceProvider.initiateAuth - CredentialsError: Missing credentials in configAWS - nodejs SDK - CognitoIdentityServiceProvider.initiateAuth - CredentialsError:配置中缺少凭证
【发布时间】:2017-08-31 08:16:21
【问题描述】:

我正在尝试使用带有用户池的 AWS Cognito 通过我的 API 进行身份验证。我有一个通过 AWS Cognito 用户池创建的用户,我正在尝试使用该用户登录。

我得到的错误是CredentialsError: Missing credentials in config。具体来说,它告诉我我需要一个IdentityPoolId。但我似乎在我的 AWS 控制台中找不到这个 IdentityPoolId。我的用户池从哪里得到这个?我看到的只是一个 Pool id 和一个 Pool ARN。

相关源码:

var aws = require('aws-sdk');
aws.config.update({
    region: 'us-east-1',
    credentials: new aws.CognitoIdentityCredentials({
        IdentityPoolId: '???'
    })
});


var authUser = function(params, callback)
{
    if (!params || !params.Email || !params._password)
    {
        callback(new Error('Invalid parameters.'));
        return false;
    }

    var cognito = new aws.CognitoIdentityServiceProvider();

    var authParams = {
        AuthFlow: 'USER_SRP_AUTH', // not sure what this means...
        ClientId: conf.AWSConfig.ClientId,
        AuthParameters: {
            Username: params.Email,
            Password: params._password
        }
    };

    cognito.initiateAuth(authParams, function(err, data)
    {
        if (err)
        {
            console.log('Error details: ' + util.inspect(err));
            callback(err);
            return false;
        }
        callback(null, {success: true, data: data});
    });
}

对于authParams 对象,我不确定AuthFlow 应该是什么。看着http://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/CognitoIdentityServiceProvider.html#initiateAuth-property,我似乎应该使用USER_SRP_AUTH

编辑:

我相信我可能已经找到了我的IdentityPoolId 的地址。我查看了我的Federated Identities 部分,并在编辑身份池时在Authentication Providers 部分下添加了相应的User Pool

我将CognitoAuthentication Provider 与我通过输入该用户池的User Pool IDApp Client ID 创建的用户池相关联。现在使用相同的代码使用Identity pool ID,我得到了错误CredentialsError: Missing credentials in config。它说Unauthorized access is not supported for this identity pool。好的...我正在尝试授权用户...我是否需要创建一个未经身份验证的角色,以便用户在未经身份验证时可以进行身份​​验证?如果这是我需要做的,那似乎很愚蠢。

编辑 2:

我还应该注意,我能够使用 Javascript SDK(不是 nodejs)登录并获得 AccessToken 以及 IdTokenRefreshToken。我这样做不需要IdentityPoolId。我唯一需要的是UserPoolIdClientId

var authenticateUser = function(onSuccessCallback)
{
    var authData = {
        Username: getUserName(), // gets username from an html text field
        Password: getPassword()  // gets password from an html password field
    };

    var authDetails = new AWSCognito.CognitoIdentityServiceProvider.AuthenticationDetails(authData);

    var cognitoUser = getCognitoUser();

    cognitoUser.authenticateUser(authDetails,
    {
        onSuccess: function(result)
        {
            console.log('access token: ' + result.getAccessToken().getJwtToken());
            console.log('idToken: ' + result.idToken.jwtToken);
            console.log(result);

            if (onSuccessCallback && typeof(onSuccessCallback) == 'function')
            {
                onSuccessCallback(cognitoUser);
            }
        },
        onFailure: function(err)
        {
            // UserNotConfirmedException: User is not confirmed.
            console.log('authError');
            alert(err);
        }
    });
}

【问题讨论】:

    标签: node.js amazon-web-services aws-cognito


    【解决方案1】:

    原来initiateAuth 根本不是我想做的。我还缺少一个名为 amazon-cognito-identity-js 的 npm 包。安装后我更新了我的代码如下:

    var authUser = function(params, callback)
    {
        if (!params || !params.Email || !params._password)
        {
            callback(new Error('Invalid parameters.'));
            return false;
        }
    
        var poolData = {
            UserPoolId: conf.AWSConfig.UserPoolId,
            ClientId: conf.AWSConfig.ClientId
        };
    
        var userPool = new aws.CognitoIdentityServiceProvider.CognitoUserPool(poolData);
        var authData = {
            Username: params.Email,
            Password: params._password
        };
    
        var authDetails = new aws.CognitoIdentityServiceProvider.AuthenticationDetails(authData);
        var userData = {
            Username: params.Email,
            Pool: userPool
        };
    
        var cognitoUser = new aws.CognitoIdentityServiceProvider.CognitoUser(userData);
    
        cognitoUser.authenticateUser(authDetails, {
            onSuccess: function(result)
            {
                callback(null, {success: true, data: result});
            },
            onFailure: function(err)
            {
                console.log('authUser error: ' + util.inspect(err));
                callback(err);
            }
        });
    }
    

    我现在成功获得了带有令牌的响应!万岁!

    【讨论】:

    • 嗨 @Jared Price 我可以在 git 上获得完整的源代码吗,因为它不适合我。
    • 新的方法是使用 aws-amplify
    • @astroanu aws-amplify 的目标是成为浏览器的库。所以,这个答案对于后端节点程序仍然是正确的。
    • @BrandonBradley 旧的 repo 现已移动未来的实现将在 amplify repo 上完成。
    • @BrandonBradley amplify 仅用于前端,对吗?同样根据答案,如果您启用了 MFA,您将如何实际将请求发送回前端,然后将代码发送回节点而不获取两个 MFA 代码?我在实现类似于答案的身份验证流程时遇到了这个问题
    【解决方案2】:

    只需使用 AWS 设置身份验证凭证并使用配置选项。

    const settings = Settings.GetSettings('Cognito');
    const auth = {
      region: settings['region'],
      apiVersion: settings['api-version'],
      accessKeyId: settings['access-key-id'],
      secretAccessKey: settings['secret-access-key']
    };
    const CognitoIdentityServiceProvider = new AWS.CognitoIdentityServiceProvider(auth);
    var config = {
      UserPoolId: settings['user-pool-id'],
      Username: guid
    };
    CognitoIdentityServiceProvider.adminDeleteUser(config, function (err, data) {
      if (err) {
        reject(err);
      } else {
        resolve(data);
      }
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-08-27
      • 2019-02-24
      • 2019-05-05
      • 2020-10-04
      • 1970-01-01
      • 1970-01-01
      • 2020-11-28
      • 1970-01-01
      相关资源
      最近更新 更多