如何使用 Cognito 保护 AWS API 网关?

How do I secure an AWS API Gateway with Cognito?

我已经设置了一个身份池并使用 Python 和 boto3 我能够检索访问密钥、秘密密钥和会话令牌,我认为这是针对未经身份验证的用户:

import boto3
boto3.setup_default_session(region_name='us-east-1')
identity = boto3.client('cognito-identity', 
                        region_name='us-east-1')

response = identity.get_id(AccountId='12344566', IdentityPoolId='us-east-1:XXXXXX')
identity_id = response['IdentityId']
print ("Identity ID: %s"%identity_id)

response = identity.get_open_id_token(IdentityId=identity_id)
token = response['Token']
print ("\nToken: %s"%(token))

resp = identity.get_credentials_for_identity(IdentityId=identity_id)
secretKey = resp['Credentials']['SecretKey']
accessKey = resp['Credentials']['AccessKeyId']

print ("\nSecret Key: %s"%(secretKey))
print ("\nAccess Key %s"%(accessKey))

获得这些详细信息后,我将尝试调用 API 网关。我使用 javascript 来完成这项任务,因为我还没有找到一种简单的方法来实现我想要的结果 python:

var apigClient = apigClientFactory.newClient({
  accessKey: 'aaaaaaaa',
  secretKey: 'kkkkkkkk',
  sessionToken: 'ssssss',
  region: 'us-east-1'
});

  apigClient.helloworldGet({},'')
  .then(function(result){
      console.log("success!: " + result);
    }).catch( function(result){
      console.log("FAIL: " + result);
    });

响应失败:

   No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access. The response had HTTP status code 403

.

随着 OPTIONS 请求的成功,我已经正确设置了 CORS。如果我使用我的主要访问密钥和秘密来验证脚本是否有效。如果我关闭 get/helloworld 方法上的 IAM 凭据要求,javascript 会成功运行。我已将策略附加到 Cognito 为身份池设置的 auth 和 unauth 角色,该策略如下所示:

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Sid": "dsfdsafasfdsfasdf",
            "Effect": "Allow",
            "Action": [
                "execute-api:Invoke"
            ],
            "Resource": [
                "arn:aws:execute-api:us-east-1:123456787:dsfsdfsdfs/dev/GET/helloworld"
            ]
        }
    ]
}

我试过将其附加为托管策略和内联策略。

我在这里错过了什么?这是否与尝试以未经身份验证的用户身份访问有关(即使分配给该类型用户的角色附加了允许其访问 API 的策略)?

请注意,此处不涉及 Lamda,只是一个位于 ECS Autoscale 组中的简单任务定义,API 网关在调用 helloworld 方法时调用该组。详情如下:https://aws.amazon.com/blogs/compute/using-amazon-api-gateway-with-microservices-deployed-on-amazon-ecs/

原来这是我检索令牌的方式。我正在使用

sessionToken = identity.get_open_id_token(IdentityId=identity_id)

我应该在请求凭据时从响应中获得令牌:

resp = identity.get_credentials_for_identity(IdentityId=identity_id)
secretKey = resp['Credentials']['SecretKey']
accessKey = resp['Credentials']['AccessKeyId']
sessionToken = resp['Credentials']['SessionToken']