如何通过 on-prem/VPN 访问私人 API 网关?

How to access private API Gateway over on-prem/VPN?

我已经创建了 API 通往 运行 Lambda 函数的网关。这意味着用作内部服务,因此我的 API 网关是私有的。为了私下访问 API 网关,我执行了以下操作:

  1. 在我们的 VPC 的几个子网中创建了一个 VPC 端点
  2. 将端点添加到仅允许来自本地的流量的安全组
  3. 向 API 网关添加了资源策略,仅允许来自 VPC 端点的请求

这些步骤有效地阻止了 public 请求,并允许通过 VPC 端点创建的 DNS 名称来自本地的请求。

此方法的问题是为了调用 API,必须在请求中指定 Hostx-apigw-api-id。目标是让用户能够继续他们的浏览器,输入 URL 和查询字符串参数,并从服务获得响应。

Amazon API Gateway types, use cases and performance 讨论了一种避免必须指定 API id 或主机的方法,但它没有提供太多细节。相关部分说解决方案是:

Place an Application Load Balancer with an SSL certificate (e.g. api.mydomain.com) in front of the IP addresses of your PrivateLink network interfaces. Also deploy a custom domain name for api.mydomain.com and a base path mapping for your API Gateway. Then add a Route 53 record that points api.mydomain.com as an alias to your ALB. This solution is quite complex, but we’ve tested it and it works. Describing the full solution is outside the scope of this post, but we might write a separate blog post about it later.

有谁知道该怎么做或其他方法吗?

我找到了这个问题的答案,所以我想我应该分享它以防其他人想知道如何做到这一点。我联系了上面写 post 的人,他给了我一些指示。他后来写了一篇 post 解释解决方案,如果我对它的总结令人困惑,你可以在这里阅读他的 post:

https://cloudbanshee.com/blog/connecting-to-private-api-over-vpn-or-vpc-peering

基本上,一旦您拥有私有 API 网关 VPC 端点和 ALB,这就是您需要做的:

  • 使用与 ALB 侦听器相同的证书创建自定义域名
  • 为要连接的 API 网关的所需阶段添加基本路径映射
  • 添加一条 route53 记录,其中自定义域名作为名称,ALB DNS 作为目标(或者如果您有自己的 DNS 服务器,请在此处添加记录
  • 为 ALB 创建 IP 类型的目标组并为 VPC 端点添加 IP
  • 在 ALB 侦听器中,创建在 url 匹配自定义域名并且路径匹配为 API 网关定义的基本路径映射时将流量发送到目标组的规则

我缺少的东西是基本路径映射。这就是 ALB 在不知道任何 ID 或主机名的情况下知道 API 将流量路由到哪个网关的方式。

我分享的post更详细,写得也更好。我建议任何有兴趣学习如何私下访问 API 网关的人阅读它。

实现此访问模式的推荐方法是将接口 VPC 端点与私有 API 网关显式关联:

aws apigateway update-rest-api \
    --rest-api-id u67n3ov968 \
    --patch-operations "op='add',path='/endpointConfiguration/vpcEndpointIds',value='vpce-01d622316a7df47f9'"
    --region us-east-1

这将创建一个新的可公开解析的 DNS 名称,该名称解析为 VPC 端点私有 IP 地址:

> nslookup u67n3ov968-vpce-01d622316a7df47f9.execute-api.us-east-1.amazonaws.com    

Non-authoritative answer:
Name:   u67n3ov968-vpce-01d622316a7df47f9.execute-api.us-east-1.amazonaws.com
Address: 10.0.0.200
Name:   u67n3ov968-vpce-01d622316a7df47f9.execute-api.us-east-1.amazonaws.com
Address: 10.0.0.155

On-premises 客户端可以使用此 DNS 名称调用私有 API 网关,而无需通过 header 或覆盖主机。