【问题标题】:How do I set up my API to require an API key with amazon API Gateway?如何设置我的 API 以要求使用 amazon API Gateway 的 API 密钥?
【发布时间】:2019-08-20 13:12:24
【问题描述】:

我一直在关注这个post 的建议我已经在 AWS 上创建了一个 API 密钥并将我的 POST 方法设置为需要一个 API 密钥。

我还设置了一个使用计划并将该 API 密钥链接到它。

我的 API 密钥已启用

当我使用邮递员测试请求时,我的请求仍然通过,没有任何额外的标头。

我希望没有请求通过,除非我在我的请求中包含这样的标题 "x-api-key":"my_api_key"

我是否需要更改我在邮递员中发送请求的端点才能通过 API 网关?

【问题讨论】:

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


    【解决方案1】:

    如果您需要为每个方法启用 API 密钥,则需要为每个方法启用 API key required true。

    转到资源--> 选择您的资源和方法,转到方法请求并将“需要 API 密钥”设置为 true。

    【讨论】:

    • 您提出了一些观点,我觉得 AWS 文档不是很友好,但我已经这样做了,我必须部署我的端点并改用 "invoke url"
    【解决方案2】:

    如果您愿意,我制作了以下脚本来为特定 API 的每个方法启用 API 密钥。它需要jq tool for advanced JSON parsing

    您可以找到script to enable the API key for all methods of an API Gateway API on this gist

    #!/bin/bash
    
    api_gateway_method_enable_api_key() {
      local api_id=$1
      local method_id=$2
      local method=$3
      aws --profile "$profile" --region "$region" \
        apigateway update-method \
        --rest-api-id "$api_id" \
        --resource-id "$method_id" \
        --http-method "$method" \
        --patch-operations op="replace",path="/apiKeyRequired",value="true"
    }
    
    # change this to 1 in order to execute the update
    do_update=0
    
    profile=your_profile
    region=us-east-1
    id=your_api_id
    tmp_file="/tmp/list_of_endpoint_and_methods.json"
    
    aws --profile $profile --region $region \
      apigateway get-resources \
      --rest-api-id $id \
      --query 'items[?resourceMethods].{p:path,id:id,m:resourceMethods}' >"$tmp_file"
    
    while read -r line; do
      path=$(jq -r '.p' <<<"$line")
      method_id=$(jq -r '.id' <<<"$line")
      echo "$path"
    
      # do not update OPTIONS method
      for method in GET POST PUT DELETE; do
        has_method=$(jq -r ".m.$method" <<<"$line")
        if [ "$has_method" != "null" ]; then
          if [ $do_update -eq 1 ]; then
            api_gateway_method_enable_api_key "$id" "$method_id" "$method"
            echo "  $method method changed"
          else
            echo "  $method method will be changed"
          fi
        fi
      done
    
    done <<<"$(jq -c '.[]' "$tmp_file")"
    

    【讨论】:

      猜你喜欢
      • 2016-12-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-09-30
      • 2016-10-06
      • 2019-01-07
      相关资源
      最近更新 更多