When I searched for Basic authentication with Lambda, I found only Node.js, so I wrote it. Also serves as a memorandum of my own. The Node.js version will come out as soon as you go around, so I won't touch it here.
It's not a big deal, but it's a rehash of the Node.js version. However, it is a little different in that it can support multiple accounts.
import json
import base64
accounts = [
{
"user": "user1",
"pass": "pass1"
},
{
"user": "user2",
"pass": "pass2"
}
]
def lambda_handler(event, context):
request = event.get("Records")[0].get("cf").get("request")
headers = request.get("headers")
authorization_header = headers.get("authorization")
if not check_authorization_header(authorization_header):
return {
'headers': {
'www-authenticate': [
{
'key': 'WWW-Authenticate',
'value':'Basic'
}
]
},
'status': 401,
'body': 'Unauthorized'
}
return request
def check_authorization_header(authorization_header: list) -> bool:
if not authorization_header:
return False
for account in accounts:
encoded_value = base64.b64encode("{}:{}".format(account.get("user"), account.get("pass")).encode('utf-8'))
check_value = "Basic {}".format(encoded_value.decode(encoding='utf-8'))
if authorization_header[0].get("value") == check_value:
return True
return False
Basically, It was easy! How to put BASIC authentication in CloudFront + S3 should be fine. There is a description of the ʻAuthorization` header that is missing from other sites here.
Recommended Posts