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

时间:2016-05-24 18:57:33

标签: javascript python-3.x amazon-web-services amazon-iam amazon-cognito

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

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);
    });

一旦我掌握了这些细节,我就会尝试调用API网关。我使用javascript完成这项任务,因为我还没有找到一种简单的方法来实现我想要的结果:

   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

.

响应失败:

{
    "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"
            ]
        }
    ]
}

我在OPTIONS请求成功时正确设置了CORS。如果我使用我的主访问密钥和秘密来验证脚本的工作原理。如果我关闭get / helloworld方法的IAM凭据要求,则javascript成功运行。我已将策略附加到Cognito为身份池设置的auth和unauth角色,此策略如下所示:

def shift(input)
  output = {}
  keys = input.keys
  0.upto(keys.size - 1) do |index|
    current = keys[index]
    if index > 0
      previous = keys[index - 1]
      output[current] = input[previous]
    else
      output[current] = []
    end
  end
  output
end

input = { a: [1, 2, 3], b: [4, 5, 6], c: [7, 8, 9] }
p shift(input)

我已尝试将其作为托管策略和内联策略附加。

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

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

1 个答案:

答案 0 :(得分:0)

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

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']