【问题标题】:How to call AWS API Gateway Endpoint with Cognito Id (+configuration)?如何使用 Cognito Id(+配置)调用 AWS API Gateway 端点?
【发布时间】:2016-08-24 02:00:21
【问题描述】:

我想使用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 请求以 200 成功,但 POST 然后以 403 失败。

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

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

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

我拥有的资源是

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

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

谢谢

【问题讨论】:

  • 您是如何使用AWS_IAM 保护网关的?我不认为这是授权人下的一个选项。

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


【解决方案1】:

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。

【讨论】:

  • 太棒了,谢谢。这是拼图中缺失的部分。
【解决方案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 });

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

【讨论】:

  • 使用 Cognito,您正在使用临时凭证。但是使用 Cognito 本身是可选的,您可以只使用标准凭据,但不建议这样做。无论如何,你可以,所以那条评论说它是可选的。
猜你喜欢
  • 2022-11-15
  • 2017-05-29
  • 2021-07-25
  • 2021-11-21
  • 2021-05-26
  • 2020-10-01
  • 1970-01-01
  • 2020-10-25
  • 2017-12-30
相关资源
最近更新 更多