CloudFront后面的API网关是否不支持AWS_IAM身份验证? [英] Does API Gateway behind CloudFront not support AWS_IAM authentication?

查看:110
本文介绍了CloudFront后面的API网关是否不支持AWS_IAM身份验证?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

似乎无法调用通过CloudFront发行版启用了AWS_IAM保护的REST API。

It seems that it is impossible to call a REST API that has AWS_IAM protection enabled through a CloudFront Distribution.

以下是重现此内容的方法:

Here is how to reproduce this:


  • 使用API​​网关创建REST API

  • 通过AWS_IAM身份验证保护REST API方法

  • 创建针对REST API的CloudFront分发

  • 在Route 53中创建针对CloudFront分发的A记录

  • create a REST API with API Gateway
  • protect a REST API method with AWS_IAM authentication
  • create a CloudFront Distribution that targets the REST API
  • create an A Record in Route 53 that targets the CloudFront Distribution

现在使用经过身份验证的用户(我使用Cognito UserPool用户和aws-amplify)进行呼叫

Now use an authenticated user (I use Cognito UserPool user and aws-amplify) to call


  1. 受保护的REST API方法及其API网关URL =成功

  2. 通过CloudFront分发URL = FAILURE

  3. 受保护的REST API通过受保护的REST API方法通过Route 53域URL的方法= FAILURE

我得到的错误是:

{ message:我们计算出的请求签名与您的签名不匹配提供。检查您的AWS Secret Access密钥和签名方法。有关详细信息,请查阅服务文档。}

{"message":"The request signature we calculated does not match the signature you provided. Check your AWS Secret Access Key and signing method. Consult the service documentation for details."}

我只是简直不敢相信AWS不支持自定义域后面的AWS_IAM保护的端点,因为这必须是非常普遍的用法-case。

I just can't believe AWS does not support AWS_IAM protected endpoints behind a custom domain since this must be a very very common use-case.

因此,您能为我提供实现此目的的详细列表吗?

Therefore could you please provide me with a detailed list of how to achieve this?

谢谢您

推荐答案

CloudFront不支持IAM auth进行分发的呼叫。正如其他人所强调的那样,SigV4依赖于主机标头和在访问您的域时,无法计算签名(无需做一些麻烦的工作,例如在客户端对API网关域进行硬编码,然后使用该标头对SigV4进行硬编码)。但是,您可以使用Lambda @ Edge函数。

CloudFront does not support IAM auth for calls hitting the distribution. As others have highlighted, SigV4 relies on the host header and there is no way to calculate a signature while hitting your domain (without doing something hacky like hardcoding the API Gateway domain on the client side and then SigV4 with that header). You can, however, add IAM from your distribution to your API using a Lambda@Edge function.

假设您已经将API Gateway设置为CloudFront发行版的来源,则需要设置 Lambda @ Edge函数拦截源请求,然后使用 SigV4 ,以便您可以限制API网关仅通过CloudFront进行访问。

Assuming that you have already setup API Gateway as an origin for your CloudFront distribution, you need to setup a Lambda@Edge function that intercepts origin requests and then signs it using SigV4 so that you can restrict your API Gateway to access only via CloudFront.

有正常HTTP请求与 CloudFront之间的转换事件格式,但都可以管理。

There is a fair amount of conversion between normal HTTP requests and the CloudFront event format but it is all manageable.

首先,创建Lambda @ Edge函数(指南),然后确保其执行角色有权访问您要访问的API网关。为简单起见,您可以在Lambda的执行角色中使用 AmazonAPIGatewayInvokeFullAccess 托管的IAM策略,使它可以调用您帐户中的任何API网关。

First, create a Lambda@Edge function (guide) and then ensure its execution role has access to the API Gateway that you would like to access. For simplicity, you can use the AmazonAPIGatewayInvokeFullAccess managed IAM policy in your Lambda's execution role which gives it access to invoke any API Gateway within your account.

然后,如果您将 aws4 用作签名客户端,这就是您的lambda代码:

Then, if you go with using aws4 as your signing client, this is what your lambda code would look like:

const aws4 = require("aws4");

const signCloudFrontOriginRequest = (request) => {
  const searchString = request.querystring === "" ? "" : `?${request.querystring}`;

  // Utilize a dummy request because the structure of the CloudFront origin request
  // is different than the signing client expects
  const dummyRequest = {
    host: request.origin.custom.domainName,
    method: request.method,
    path: `${request.origin.custom.path}${request.uri}${searchString}`,
  };

  if (Object.hasOwnProperty.call(request, 'body')) {
    const { data, encoding } = request.body;
    const buffer = Buffer.from(data, encoding);
    const decodedBody = buffer.toString('utf8');

    if (decodedBody !== '') {
      dummyRequest.body = decodedBody;
      dummyRequest.headers = { 'content-type': request.headers['content-type'][0].value };
    }
  }

  // Use the Lambda's execution role credentials
  const credentials = {
    accessKeyId: process.env.AWS_ACCESS_KEY_ID,
    secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY,
    sessionToken: process.env.AWS_SESSION_TOKEN
  };

  aws4.sign(dummyRequest, credentials); // Signs the dummyRequest object

  // Sign a clone of the CloudFront origin request with appropriate headers from the signed dummyRequest
  const signedRequest = JSON.parse(JSON.stringify(request));
  signedRequest.headers.authorization = [ { key: "Authorization", value: dummyRequest.headers.Authorization } ];
  signedRequest.headers["x-amz-date"] = [ { key: "X-Amz-Date", value: dummyRequest.headers["X-Amz-Date"] } ];
  signedRequest.headers["x-amz-security-token"] = [ { key: "X-Amz-Security-Token", value: dummyRequest.headers["X-Amz-Security-Token"] } ];

  return signedRequest;
};

const handler = (event, context, callback) => {
  const request = event.Records[0].cf.request;
  const signedRequest = signCloudFrontOriginRequest(request);

  callback(null, signedRequest);
};

module.exports.handler = handler;

这篇关于CloudFront后面的API网关是否不支持AWS_IAM身份验证?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆