Recently I came across a usecase where I had to restrict access to a website in the UAT environment, so that the iterations and changes to the UAT env are not available for public view. The website was served with the CloudFront CDN, so one of the ways we could restrict access was enforcing authentication on the Cloudfront Distribution using Lambda@Edge.
How did I achive this?
Create a Lambda Function
- Go to us-east-1 region as that is the only region we can deploy Lambda@Edge functions.
- Go to the AWS Console and choose Lambda from services.
- Create function and author from scratch.
- Provide function name, and select Node JS 14.x as runtime.
- In Change Default Execution Role, create a new role with basic Lambda permissions.
Boom! Your function is created.
- Use the below code and replace the user and password with your required username and password. code
- Deploy the code.
- Go to general configuration in Configuration and change the function timeout to 5sec, that's the max allowed timeout for CDN triggered Lambda Function.
- Go to Permissions, and open the IAM role, and update the Trust Relationships with the below json snippet, which allows lambda and lambda@edge to assume the role.
- Go to Actions, and under capabilities, select Deploy to Lambda@Edge.
- Configure a new Cloudfront Trigger, select your distribution under Cloudfront event and select a Viewer request, then check include body, and confirm deploy to Lambda@Edge.
It shall take few minutes to enforce the authentication, once done we can see a sign in option as we try to access our UAT env website, provide the username and password you used in the code and access your website. (to not disclose our client, I have used a dummy CloudFront URL with my content)
If you face any challenges please connect and discuss with me on Linkedin
Also I'm currently part of the Save Soil Movement initiated by the Isha Foundation, I know you are aware of the conditions of the soil and as a generation we have to turn this around, Become an Earth Buddy
Stay Joyful! :)