お問い合わせ

Implement Basic AUth using lambda function for S3 Website Hosting

制作・開発
profile

Muntasir Ahmed MUFTI

Implement Basic Auth using lambda function for S3 Website Hosting

To implement basic authentication in AWS CloudFront using a Lambda@Edge function written in Python, follow these steps:

  1. Create the Lambda Function:
    • Write the Lambda function that will handle the authentication.
    • This function will decode the Authorization header and check the credentials.
  2. Deploy the Lambda Function:
    • Deploy the Lambda function in the AWS Lambda console.
    • Ensure it is available in the us-east-1 region because Lambda@Edge functions must be replicated from this region.
  3. Attach the Lambda Function to CloudFront:
    • Create a CloudFront distribution or update an existing one to include the Lambda function as a trigger.

Here’s a step-by-step guide to achieve this:

Step 1: Create the Lambda Function

import base64

def lambda_handler(event, context):

    # Get the request object

    request = event['Records'][0]['cf']['request']

    # Get the headers

    headers = request['headers']

    # Define the username and password

    USERNAME = 'your_username'

    PASSWORD = 'your_password'

    # Encode the username and password

    auth_string = f"{USERNAME}:{PASSWORD}"

    encoded_auth_string = base64.b64encode(auth_string.encode()).decode()

    # Check for Authorization header

    if 'authorization' in headers:

        auth_header = headers['authorization'][0]['value']

        # Check if the Authorization header matches the encoded auth string

        if auth_header == f"Basic {encoded_auth_string}":

            return request

    # If no valid Authorization header is present, return a 401 Unauthorized response

    return {

        'status': '401',

        'statusDescription': 'Unauthorized',

        'headers': {

            'www-authenticate': [{'key': 'WWW-Authenticate', 'value': 'Basic'}],

            'content-type': [{'key': 'Content-Type', 'value': 'text/html'}]

        },

        'body': '<html><body><h1>Unauthorized</h1></body></html>'

    }

Step 2: Deploy the Lambda Function

  1. Go to the AWS Lambda Console.
  2. Click “Create function”.
  3. Choose “Author from scratch”.
  4. Enter a function name and select Python 3.x as the runtime.
  5. Click “Create function”.
  6. Copy and paste the above code into the function code editor.
  7. Click “Deploy”.

Step 3: Attach the Lambda Function to CloudFront

  1. Go to the AWS CloudFront Console.
  2. Select the CloudFront distribution you want to secure.
  3. Click on the “Behaviors” tab.
  4. Select the behavior you want to apply the authentication to and click “Edit”.
  5. In the “Lambda Function Associations” section, select “Viewer Request” for the event type.
  6. Choose the Lambda function you just created.
  7. Click “Yes、 Edit”.

Notes

  • Ensure your Lambda function is in the us-east-1 region for Lambda@Edge to work.
  • Adjust the USERNAME and PASSWORD variables to your desired credentials.
  • Remember that basic authentication is not very secure. For production environments, consider using more secure methods like OAuth or JWT.

This setup will check for basic authentication on each viewer request. If the credentials are correct, the request will proceed to CloudFront. If not, it will return a 401 Unauthorized response.

======= If you get the following type Error , then follow next steps ========

To update the IAM role to include the necessary permissions for edgelambda.amazonaws.com and lambda.amazonaws.com principals, you need to adjust the trust relationship of the IAM role. Here are the steps to do this:

Step 1: Update the Trust Relationship

  1. Go to the AWS IAM Console.
  2. In the left sidebar, click on “Roles”.
  3. Search for the role pythonbaseauth-role-6qoa0e7x.
  4. Click on the role name to open the role details.
  5. Click on the “Trust relationships” tab.
  6. Click the “Edit trust relationship” button.

Step 2: Modify the Trust Relationship Policy Document

You need to ensure the trust relationship includes both edgelambda.amazonaws.com and lambda.amazonaws.com. Here is the updated trust relationship policy document:

{

  "Version": "2012-10-17",

  "Statement": [

    {

      "Effect": "Allow",

      "Principal": {

        "Service": "lambda.amazonaws.com"

      },

      "Action": "sts:AssumeRole"

    },

    {

      "Effect": "Allow",

      "Principal": {

        "Service": "edgelambda.amazonaws.com"

      },

      "Action": "sts:AssumeRole"

    }

  ]

}

{

 

Replace the existing trust relationship policy document with the above JSON and click “Update Trust Policy”.

Step 3: Ensure the Role Has Necessary Permissions

Make sure the IAM role has the necessary permissions to execute the Lambda function. Attach the AWSLambdaBasicExecutionRole policy if it’s not already attached.

  1. Go to the “Permissions” tab.
  2. Click “Attach policies”.
  3. Search for and attach the AWSLambdaBasicExecutionRole policy.

Step 4: Retry Deploying the Lambda@Edge Function

Once the trust relationship is updated and the necessary permissions are attached, you can retry deploying the Lambda@Edge function to your CloudFront distribution.