Configure Basic Authentication for CloudFront Using Lambda@Edge
For web servers, you must know the basic authentication settings for LAMP configuration. What if you are using AWS Cloudfront for hosting your frontend part? How will you add basic authentication for CloudFront? The answer is AWS Lambda function.
This article will lead you to step by step procedures for configuring basic authentication with Lambda@Edge. S3 bucket representing contents through CloudFront may be blocked due to basic authentication requirement. Sometimes, browsers (chrome, safari) may not load png or jpg files. In this article, certain issues are kept under consideration and tried to provide a solution for that.
Step 1: Select AWS Region
At first, you need to select the AWS Region. My suggestion is to use region N.Virginia. Why? Even if you can’t configure it yourself, you can get help from the Lambda blueprint. Blueprint has a template to create basic authentication using a Lambda function. You can type the CloudFront and the list narrowed down like below picture. Then you can use CloudFront response generation. We shall discuss this in another article.
Step 2: Create Function on Lamda
Open AWS Lambda service in N. Virginia Region and click on Create Function. Then you need to Select Author from scratch. Provide your Desired Function Name and keep runtime as Node.js 10.x. Lastly type Create.
Step 3: Code in index.js
Once you are done creating the Lambda function you will get a window like this one:
In the index.js file remove the existing code and type the following as below:
Then click on ‘Save’ on the top right corner. Click on ‘Actions’. And from the drop-down list select “Publish New Version” and provide a name for the version.
Step 4: Configure Trigger Option
Select “Add trigger”.
Do the following in the trigger configuration.
- Cloudfront from the drop-down list.
- From Distribution Dropdown list Select the CloudFront you wish to use for basic authentication.
- Keep Cache Behavior with ‘*’.
- Select ‘Viewer Request’ From ‘CloudFront event’.
- Tick the Acknowledgement Windows.
Step 5: Configure ‘Trust Relation’ in IAM Role
Then open another Tab of AWS and Open IAM. Click on Roles and select the role you have created. Then click on the ‘Trust Relation’ Tab and edit with the following:
After this, click on update trust policy.
Final Step: Activate AWS Lamda@Edge for Basic Authentication
For the last step, go back to Lambda Page and create ‘Add’. You are done and good to go.
Browse your URL of CloudFront or the domain associated with it. You will find it with basic authentication available. You need to test with all our browsers.
If you have anything more to discuss, feel free to ping me at istiaque.islam@monstar-lab.com.bd.
Visit our website to learn more about us:
www.monstar-lab.co.bd