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/awscli

Deploy

Set your Region, <code>export AWS_REGION=us-east-1</code>, then run <code>./deploy.sh</code>.The script deploys the Web Function with <code>aws lambda-web deploy --auth-type IamAuth</code>, creates the OAC, a cache policy that forwards the viewer's Authorization header, and the distribution, attaches the resource policy and waits for the distribution to deploy.


Testing

See the GitHub repo for detailed testing instructions.

Cleanup

Disable and delete the CloudFront distribution, then delete the cache policy and the OAC, then aws lambda-web delete-web-function --function-name lambda-web-cloudfront-oac.
See the GitHub repo for removing the execution role and log groups.

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