【问题标题】:Using AWS Boto3 Invoke API Gateway from EC2 Instance使用 AWS Boto3 从 EC2 实例调用 API Gateway
【发布时间】:2020-08-09 19:25:55
【问题描述】:

我正在尝试从具有 IAM 角色的 EC2 实例之一调用 AWS API Gateway 端点。我在 EC2 实例上安装了 boto3 库,并尝试使用以下代码执行简单的网关 API,但仍然出现 Authentication missing 错误。

import boto3
import json
import requests
from aws_requests_auth.aws_auth import AWSRequestsAuth

session = boto3.Session()
credentials = session.get_credentials()

headers = {'params': 'ABC'}
response = requests.get('https://restapiid.execute-api.us-east-1.amazonaws.com/stage/resource_path',
                        auth=credentials, headers=headers)

这对于具有 IAM 角色的 EC2 实例应该非常简单。请大家多多指教。

【问题讨论】:

  • 你可以用 session.get_credentials().get_frozen_credentials() 替换 session.get_credentials() 并再试一次吗?如果它仍然不起作用,请使用错误详细信息更新您的问题

标签: python-requests aws-api-gateway boto3


【解决方案1】:

由于您的问题中缺少详细信息,(缺少实例角色详细信息、API 网关策略、未知headers 或启用了iam_auth)我只能提供和评论给出的 python 代码。

使用角色的python代码应该是(这是我用来验证代码的例子):

import boto3
import requests
from aws_requests_auth.aws_auth import AWSRequestsAuth

session = boto3.Session()
credentials = session.get_credentials()

auth = AWSRequestsAuth(aws_access_key=credentials.access_key,
                       aws_secret_access_key=credentials.secret_key,
                       aws_token=credentials.token,
                       aws_host='fzoskzctgd.execute-api.us-east-1.amazonaws.com',
                       aws_region='us-east-1',
                       aws_service='execute-api')


response = requests.get('https://fzoskzctgd.execute-api.us-east-1.amazonaws.com/test', auth=auth)

print(response.content)

我测试了这个,将authorizationType 设置为AWS_IAM 用于测试的资源。

API 资源政策

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Effect": "Allow",
            "Principal": {
                "AWS": "arn:aws:iam::123456:role/instance-role"
            },
            "Action": "execute-api:Invoke",
            "Resource": "arn:aws:execute-api:us-east-1:170576413884:fzoskzctgd/test/*"
        }
    ]
}

实例角色

不需要任何 api 调用权限,因为它们是通过 API 资源策略提供的。 instance-role 必须只存在并附加到实例。

【讨论】:

    猜你喜欢
    • 2016-08-20
    • 2016-07-23
    • 2021-02-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多