
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/samCreate a versioning-enabled S3 bucket whose policy lets lambda.amazonaws.com read objects, zip <code>src/</code> and upload it, then run <code>sam deploy --stack-name lambda-web-cloudfront-oac-sam --capabilities CAPABILITY_IAM --s3-bucket <bucket> --parameter-overrides CodeBucket=<bucket> CodeKey=<key></code>.One template creates the Web Function with an <code>IamAuth</code> endpoint, the OAC, a cache policy that forwards the viewer's Authorization header, the CloudFront distribution and the resource policy; see the GitHub repo for the bucket setup.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.