はじめに
LambdaでBasic認証って検索すると、Node.jsのものしか見つからなかったので書いてみた。
自身の備忘録も兼ねて。
Node.js版は、ぐぐるとすぐに出てくるので、ここでは触れないです。
コード
と言っても大したものではなく、Node.js版の焼き直しな感じです。
ただ、マルチアカウントに対応できるようになっている点はちょっと違う。
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
設定たち
基本的に、簡単だった!CloudFront + S3 に BASIC認証を入れる方法 を見たら問題ないはず。
他のサイトでは抜けている Authorization
ヘッダの記述がここにはあるので。