【问题标题】:Adding Headers to AWS API Gateway Response using Chalice使用 Chalice 向 AWS API Gateway 响应添加标头
【发布时间】:2018-12-10 15:40:44
【问题描述】:

我的用例要求我的应用在错误响应为 401 时返回 CORS 标头。

AWS 去年添加了此功能 (See this)。可以使用 Cloudformation 和 Swagger 模板完成,但我不确定是否可以使用 Chalice。

【问题讨论】:

    标签: amazon-web-services aws-api-gateway amazon-cognito custom-headers chalice


    【解决方案1】:

    我使用 python 脚本解决了我的问题,该脚本为 401 响应添加 CORS 标头并重新部署 API。重新部署 API 需要一两秒钟,因为它不必像 Chalice 那样部署所有 Lambda。

    deploy.sh

    #!/usr/bin/env bash
    
    cd services
    A="$(chalice deploy --stage $1)"
    cd ..
    python update_api_response_headers.py "$A" "$1"
    

    update_api_response_headers.py

    import boto3
    import sys
    import re
    
    if len(sys.argv) != 3:
        print("usage: python script.py <CHALICE_DEPLOYMENT_RESULT> <STAGE>")
        exit()
    
    search = re.search('URL: https:\\/\\/([a-zA-Z0-9]+).+', sys.argv[1])
    api_id = search.group(1)
    print(api_id)
    if not api_id:
        print(sys.argv[1])
        exit()
    client = boto3.client('apigateway')
    
    response = client.put_gateway_response(
        restApiId=api_id,
        responseType='UNAUTHORIZED',
        statusCode='401',
        responseParameters={
            "gatewayresponse.header.Access-Control-Allow-Origin": "'*'",
            "gatewayresponse.header.Access-Control-Allow-Headers": "'*'"
        }
    )
    response = client.create_deployment(
        restApiId=api_id,
        stageName=sys.argv[2])
    
    print(sys.argv[1])
    

    Services 文件夹包含我的圣杯应用程序。 deploy.shupdate_api_response_headers.py 位于 chalice 应用程序的上一层。要部署应用程序,我只需要使用:

    ./deploy.sh stage_name
    

    【讨论】:

      猜你喜欢
      • 2019-08-12
      • 2017-05-18
      • 2021-04-06
      • 2016-12-15
      • 2017-10-01
      • 1970-01-01
      • 2021-09-30
      • 2021-12-20
      • 2015-10-21
      相关资源
      最近更新 更多