AWS Cloudfront (with WAF) + API Gateway: how to force access through Cloudfront?

You can use custom domain name and point DNS to the distribution with WAF. Requests directly to the original API Gateway distribution will not work then.


The "right" way would be to use the custom authorizor in API Gateway as mentioned by others.

The "cheap" way would be bullet 3, an api key. You would probably only provision waf -> cloudfront -> api gateway if you were trying to fend off a ddos attack. So if someone discovered your api gateway url and decided to ddos that instead of cloudfront, a custom authorizor means you are now taking the brunt of the attack on lambda. Api gateway can handle over 10k requests per second, the default lambda limit is 100 per second. Even if you got amazon to increase your limit are you willing to pay for 10k lambda's per second for a sustained attack?

AWS reps will tell you, "API Keys are for identification, not for authentication. The keys are not used to sign requests, and should not be used as a security mechanism" https://aws.amazon.com/blogs/aws/new-usage-plans-for-amazon-api-gateway/

But honestly if you are not going to do something better in your lambda than validate some giant jumbled string why not leave that burden and cost to someone else. (Max key length is 128 characters)

Maybe you could have a scheduled lambda function to issue a new api key and update cloudfront's header every 6 hours?

If you want to use api keys for other things then just have one api gateway origin for authentication, and another origin and api gateway for everything else. This way in a ddos attack you can handle 10k request per second to your auth api, while all other customers who are already logged in have a collective 10k per second to use your api. Cloudfront and waf can handle 100K per second so they won't hold you back in this scenario.

One other thing of note if you are using lambda behind api gateway, you could use lambda@edge and just skip api gateway all together. (This won't fit most scenarios because lambda@edge is severely limited, but I figured I would throw it out there.)

But ultimately WE NEED WAF INTEGRATION WITH API GATEWAY!! : )


It is possible to force access through CloudFront via using a Lambda@Edge function for SigV4 signing origin requests and then enabling IAM auth on your API Gateway. This strategy is able to be used in conjunction with API Keys in your CloudFront distribution (guide for CloudFront+API Key).

Assuming that you have already setup API Gateway as an origin for your CloudFront distribution, you first need to create a Lambda@Edge function (guide for Lambda@Edge setup) 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.

Then, if you go with using aws4 as your signing client, this is what your Lambda@Edge 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}`,
  };

  // Include the body in the signature if present
  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;

Note that if you you include a body in your request, you have to manually configure your Lambda@Edge function to include the body via the console or SDK or setup a CloudFormation custom resource to call the SDK since CloudFormation does not support enabling this natively yet


I am from API Gateway.

Unfortunately, the best solution we have as of now is, to inject an origin custom header in CloudFront and validate that in a custom authorizer (option 4 in your question).

We are already aware of this limitation and not-so-great workaround. We are looking to provide better WAF integration in future, but we do not have an ETA.