了解身份服务

Cognito Identity Service

我需要创建用户并获取临时凭据才能使用其他服务 (cloudWatch)? 如何获得临时凭证?如果我使用我的凭据,这是可行的,但这不安全。

import * as AWS from 'aws-sdk';

AWS.config.region = 'region';
var credentials = new AWS.CognitoIdentityCredentials({
    AccountId: 'accountId',
    RoleArn: 'role',
    IdentityPoolId: 'pool',
});

AWS.config.credentials = credentials;
AWS.config.update({accessKeyId: 'anything', secretAccessKey: 'anything'});
// AWS.config.update({accessKeyId: 'key', secretAccessKey: 'secretKey'});
var cognitoidentity = new AWS.CognitoIdentity({apiVersion: '2014-06-30'});
var cognitoidentityserviceprovider = new AWS.CognitoIdentityServiceProvider({apiVersion: '2016-04-18'});

get(){
var paramsCreateUser = {
      UserPoolId: 'pool',
      Username: 'name',
      UserAttributes: [{
        Name: 'email',
        Value: 'e@gmail.com'
      }]
    };

    cognitoidentityserviceprovider.adminCreateUser(paramsCreateUser, function(err, data) {
      if (err) console.log(err, err.stack);
      else     console.log(data);
    });
}

不要在 Lambda 中设置您的 AWS 凭证。您应该创建 Lambda 执行的 IAM 角色,它具有您的函数所需的权限。参见 Loading Credentials for a Node.js Lambda Function

When you create an AWS Lambda function, you must create a special IAM role that has permission to execute the function. This role is called the execution role. When you set up a Lambda function, you must specify the IAM role you created as the corresponding execution role.

The execution role provides the Lambda function with the credentials it needs to run and to invoke other web services. As a result, you do not need to provide credentials to the Node.js code you write within a Lambda function.

  1. 进入 IAM。创建一个新角色,我们称之为 'lambda-create-cognito-user'
  2. 将策略 'AWSLambdaBasicExecutionRole' 和 'AmazonCognitoPowerUser' 分配给角色
  3. 进入 Lambda 控制台并将函数设置为 'lambda-create-cognito-user'
  4. 执行

编辑:如果您需要访问其他服务,只需将所需的策略添加到 IAM 角色。例如,您可以添加策略 'CloudWatchFullAccess'.