如何使用Cognito Id(+配置)调用AWS API Gateway Endpoint?

时间:2016-04-29 04:03:51

标签: amazon-web-services aws-sdk amazon-iam amazon-cognito aws-api-gateway

我想使用AWS API Gateway Endpoint拨打受 AWS_IAM 保护的generated JavaScript API SDK

我有 Cognito UserPoolCognito 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请求会以200成功,但POST会因403而失败。

我很确定此处没有CORS问题。

我非常确定问题与IAM RolesAWS Resource Configurations

有关

我的问题基本上是,您能否请我提供所需的所有必要AWS Resource ConfigurationsIAM Roles吗?

我的资源是

  • API网关 - 使用已部署的API端点
  • Lambda函数 - 由端点调用
  • Cognito用户池 - 同步应用于身份池
  • Cognito Identity Pool - 将授权和未授权角色映射到它。
  • IAM角色 - 用于Lambda函数以及Cognito身份池的授权和未授权角色。

但我不知道如何正确配置这些资源以使其发挥作用。

谢谢

2 个答案:

答案 0 :(得分:3)

Cognito Identity的角色具有哪些访问权限?确保它有权在您的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。

答案 1 :(得分:2)

即使遵循了所有内容,我也会遇到同样的错误。原因是我在初始化apigClient时错过了“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 });

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