Note: Environment variables are not supported on Lambda@Edge: AWS Edge functions restrictions
import base64
def lambda_handler(event, context):
# Get the CloudFront request
request = event['Records'][0]['cf']['request']
# Add the authorization header is not set (default to an empty string)
request['headers']['authorization'] = request['headers'].get('authorization', [{'key': 'authorization', 'value': ''}])
# This is the expecteded authorization header
expected_authorization = 'Basic ' + base64.b64encode("<login>:<password>".encode()).decode()
# Test if the authorization header is not matching (401 response in this case)
if request['headers']['authorization'][0]['value'] != expected_authorization:
return {
'status': '401',
'statusDescription': 'Unauthorized',
'body': 'Unauthorized',
'headers': {
'www-authenticate': [{'key': 'WWW-Authenticate', 'value': 'Basic'}]
}
}
# The authorization header is matching, forward the request
return request