【问题标题】:How do I get a pre-signed url for an API Gateway in Cloudformation using Boto3?如何使用 Boto3 在 Cloudformation 中获取 API 网关的预签名 URL?
【发布时间】:2017-11-08 09:35:30
【问题描述】:

我想调用 Cloudformation 中维护的 API 网关。我有 Cloudformation 堆栈名称 (CF_STACK_NAME)、API 网关资源名称 (API_GATEWAY_NAME),以及我需要承担的 IAM 角色的 Cloudformation 名称 (API_ROLE_NAME)。

我可以通过以下方式访问我的 Cloudformation 堆栈,

cf_client = boto3.client('cloudformation')
api_role_resource = cf_client.describe_stack_resource(
       StackName=CF_STACK_NAME,
       LogicalResourceId=API_ROLE_NAME
)
api_resource = cf_client.describe_stack_resource(
       StackName=CF_STACK_NAME,
       LogicalResourceId=API_GATEWAY_NAME
)

通过阅读Switching to an IAM Role,我了解了如何获取我的角色密钥,

sts_client = boto3.client('sts')
credentials = sts_client.assume_role(
    RoleArn='arn:aws:iam::{account_id}:role/{role_name}'.format(
        account_id=sts_client.get_caller_identity().get('Account'),
        role_name=api_role_resource['PhysicalResourceId']
    ),
    RoleSessionName="AssumeRoleSession1"
)['Credentials']

但是当我想调用API url时,

apigateway_client     = boto3.client('apigateway')
restapi_id = apigateway_client.get_rest_api(restApiId=api_logical_id)['id']
url = f'https://{restapi_id}.execute-api.{region}.amazonaws.com/{stage}/{api_query}

api_output = requests.get(url).json()

我明白了,

An error occurred (AccessDeniedException) when calling the GetRestApi operation: User: arn:aws:iam::0123456789:user/my-user is not authorized to perform: apigateway:GET on resource: arn:aws:apigateway:us-west-2::/restapis/ServerlessRestApi

如何使用此 CloudFormation 信息进行 API 调用?

【问题讨论】:

    标签: amazon-web-services aws-api-gateway amazon-cloudformation


    【解决方案1】:

    我的猜测是您没有使用来自 STS 的新凭据。

    您需要使用如下代码使用新凭据创建 apigateway 客户端:

    client = boto3.client(
           'apigateway',
            aws_access_key_id=credentials['Credentials']['AccessKeyId'],
            aws_secret_access_key=credentials['Credentials']['SecretAccessKey'],
            aws_session_token=credentials['Credentials']['SessionToken'])
    

    【讨论】:

    • 为了真正进行 API 调用,这个客户端会生成一个签名的 URL 吗?
    • @aidan。我不明白你的问题。
    • 所以我认为你回答了我的部分问题。我希望像 url = f'https://{restapi_id}.execute-api.{region}.amazonaws.com/{stage}/{api_query} 这样调用 api,但我相信我需要凭据才能拨打电话。还是我弄错了?
    • 答案取决于您如何配置 API 网关。您打算从 Web 浏览器还是从 boto3 客户端 API 调用 apigateway?我会重做您的问题,以便更清楚地了解您要做什么。
    • 没关系。现在问题就在我这边,超出了这个问题的范围。我们需要修正一些政策。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-11-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多