
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.
IamAuth authentication type, so Lambda accepts only requests signed with AWS Signature Version 4 and returns 403 to everything else before your code runs.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.Cache-Control headers that CloudFront honours, which the pattern uses to show edge caching.This pattern is available in the following frameworks/languages:
git clone https://github.com/aws-samples/serverless-patterns/cd serverless-patterns/lambda-web-cloudfront-oac/nodejs/samRun sam build, then sam deploy --stack-name lambda-web-cloudfront-oac-sam --capabilities CAPABILITY_IAM --resolve-s3. Requires AWS SAM CLI 1.171.0 or later.CodeUri is the local src/ directory, so the AWS SAM CLI builds the code and uploads it to a versioning-enabled, Lambda-readable bucket it creates for the stack. One template creates the Web Function with an IamAuth endpoint, the OAC, a cache policy that forwards the viewer's Authorization header, the CloudFront distribution and the resource policy.sam delete --stack-name lambda-web-cloudfront-oac-sam. CloudFormation disables and removes the distribution, the cache policy, the OAC and the function with its endpoint and resource policy.sam delete also empties and removes the code bucket stack. See the GitHub repo for removing the log groups.