AWS Lambda Web Function behind Amazon CloudFront with Origin Access Control

Client → Amazon CloudFront → AWS Lambda Web Function

Serve a Lambda Web Function only through a CloudFront distribution: an IamAuth endpoint, an OAC that signs origin requests, and a resource policy that trusts one distribution.

This pattern deploys a plain Node.js HTTP server as an AWS Lambda Web Function and puts an Amazon CloudFront distribution in front of it. The function's endpoint uses the IamAuth authentication type, so Lambda accepts only requests signed with AWS Signature Version 4 and returns 403 to everything else before your code runs.
CloudFront signs each origin request through an Origin Access Control of type lambda with SigningBehavior: always-amz-auth. A resource policy on the function allows lambda:InvokeWebFunctionEndpoint for the CloudFront service principal only when AWS:SourceArn matches your distribution, so a different distribution using the same origin is also denied.
After validating the signature, Lambda removes the Authorization header it used and forwards the viewer's own headers, so the application has no authentication code of its own and existing sign-in flows keep working. The app returns Cache-Control headers that CloudFront honours, which the pattern uses to show edge caching.
With CloudFront in front you can add a custom domain, AWS WAF, compression and caching to a Web Function without changing the application.

< Back to all patterns
AWS Top Pick

GitHub icon Download this pattern (.zip)

GitHub icon View this pattern on GitHub

Variants

This pattern is available in the following frameworks/languages:

AWS CDK:Node.js
AWS CLI:Node.js
AWS SAM:Node.js

Clone repo

git clone https://github.com/aws-samples/serverless-patterns/cd serverless-patterns/lambda-web-cloudfront-oac/nodejs/cdk

Deploy

Run <code>npm install</code>, then <code>cdk deploy</code> in the pattern directory (bootstrap the account and Region first if needed).The stack creates the versioned code bucket, uploads the application, and defines the Web Function, its revision and <code>IamAuth</code> endpoint, the OAC, a cache policy that forwards the viewer's Authorization header, the CloudFront distribution and the resource policy.


Testing

See the GitHub repo for detailed testing instructions.

Cleanup

Run cdk destroy. The stack disables and deletes the distribution and the cache policy, empties and deletes the code bucket and removes the log group.

Created by:

Jon Loinaz Anton

Jon Loinaz Anton

Enterprise Solutions Architect at AWS based in Spain, helping large organizations adopt serverless and generative AI.

Follow on LinkedIn