如何使用 Cognito Id(+配置)调用 AWS API 网关端点?

How to call AWS API Gateway Endpoint with Cognito Id (+configuration)?

我想使用 generated JavaScript API SDK.

调用受 AWS_IAM 保护的 AWS API Gateway Endpoint

我有一个 Cognito UserPool 和一个 Cognito Identity Pool。两者都通过 ClientId.

正确同步

我使用此代码 Sign in 并获得 Cognito Identity

AWS.config.region = 'us-east-1'; // Region
AWS.config.credentials = new AWS.CognitoIdentityCredentials({
  IdentityPoolId: 'us-east-1:XXXXXXXXXXXXXXXXXXXXXXXX' // your identity pool id here
});

AWSCognito.config.region = 'us-east-1';
AWSCognito.config.credentials = new AWS.CognitoIdentityCredentials({
  IdentityPoolId: 'us-east-1:XXXXXXXXXXXXXXXXXXXXXXXX' // your identity pool id here
});

var poolData = {
  UserPoolId: 'us-east-1_XXXXXXXX',
  ClientId: 'XXXXXXXXXXXXXXXXXXXXXXXX'
};
var userPool = new AWSCognito.CognitoIdentityServiceProvider.CognitoUserPool(poolData);


var authenticationData = {
  Username: 'user',
  Password: '12345678',
};
var authenticationDetails = new AWSCognito.CognitoIdentityServiceProvider.AuthenticationDetails(authenticationData);
var userData = {
  Username: 'user',
  Pool: userPool
};
var cognitoUser = new AWSCognito.CognitoIdentityServiceProvider.CognitoUser(userData);
cognitoUser.authenticateUser(authenticationDetails, {
  onSuccess: function (result) {
  console.log('access token + ' + result.getAccessToken().getJwtToken());

  AWS.config.credentials = new AWS.CognitoIdentityCredentials({
    IdentityPoolId: 'us-east-1:XXXXXXXXXXXXXXXXXXXX',
    IdentityId: AWS.config.credentials.identityId,
    Logins: {
      'cognito-idp.us-east-1.amazonaws.com/us-east-1_XXXXXX': result.idToken.jwtToken
    }
  });

  AWS.config.credentials.get(function (err) {
    // now I'm using authenticated credentials
    if(err)
    {
      console.log('error in autheticatig AWS'+err);
    }
    else
    {
      console.log(AWS.config.credentials.identityId);

    }
  });
  },

  onFailure: function (err) {
    alert(err);
  }

});

这一切都成功了,我现在有一个 authorized Cognito Identity

现在我尝试调用 API Gateway Endpoint 来执行它指向的 Lambda Function

  var apigClient = apigClientFactory.newClient({
    accessKey: AWS.config.credentials.accessKeyId, //'ACCESS_KEY',
    secretKey: AWS.config.credentials.secretAccessKey, //'SECRET_KEY',
    sessionToken: AWS.config.credentials.sessionToken, // 'SESSION_TOKEN', //OPTIONAL: If you are using temporary credentials you must include the session token
    region: 'us-east-1' // OPTIONAL: The region where the API is deployed, by default this parameter is set to us-east-1
  });

  var params = {
    // This is where any modeled request parameters should be added.
    // The key is the parameter name, as it is defined in the API in API Gateway.
  };

  var body = {
    // This is where you define the body of the request,
    query: '{person {firstName lastName}}'
  };

  var additionalParams = {
    // If there are any unmodeled query parameters or headers that must be
    //   sent with the request, add them here.
    headers: {},
    queryParams: {}
  };

  apigClient.graphqlPost(params, body, additionalParams)
    .then(function (result) {
      // Add success callback code here.
      console.log(result);
    }).catch(function (result) {
    // Add error callback code here.
    console.log(result);
  });

但不幸的是,这失败了。 OPTIONS 请求成功 200POST 然后失败 403.

我很确定这里没有CORS问题。

我很确定问题与 IAM RolesAWS Resource Configurations 有关。

我的问题基本上是,能否请您提供所有必要的 AWS Resource ConfigurationsIAM Roles 才能正常工作?

我拥有的资源是

但我不知道如何正确配置这些资源才能使其正常工作。

谢谢

Cognito 身份角色有哪些访问权限?确保它有权在您的 API.

上执行 execute-api:Invoke
{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Allow",
      "Action": [
        "execute-api:Invoke"           
      ],
      "Resource": [
        "arn:aws:execute-api:us-east-1:<account>:<rest-api>/*/POST/graphql"
      ]
    }
  ]
} 

您可以从 Web 控制台的方法设置页面获取准确的资源 ARN。

即使按照所有步骤进行操作,我仍然遇到相同的错误。原因是我在初始化 apiClient 时错过了 "sessionToken"。

var apigClient = apigClientFactory.newClient({
accessKey: AWS.config.credentials.accessKeyId, //'ACCESS_KEY',
secretKey: AWS.config.credentials.secretAccessKey, //'SECRET_KEY',
sessionToken: AWS.config.credentials.sessionToken, // 'SESSION_TOKEN', //OPTIONAL: If you are using temporary credentials you must include the session token
region: 'us-east-1' // OPTIONAL: The region where the API is deployed, by default this parameter is set to us-east-1 });

//可选:如果您使用的是临时凭据,则必须包含会话令牌——实际上并不是可选的