【问题标题】:How do I secure an AWS API Gateway with Cognito?如何使用 Cognito 保护 AWS API 网关?
【发布时间】:2016-09-22 03:35:33
【问题描述】:

我已经设置了一个身份池,并使用 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/

【问题讨论】:

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


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 2020-04-18
      • 1970-01-01
      • 2018-07-24
      • 2017-09-19
      • 2020-12-12
      • 2018-09-13
      • 2017-11-23
      • 1970-01-01
      • 2022-01-26
      相关资源
      最近更新 更多