I'm developing my first AWS serverless Python app and I need a something that processes and checks some of the HTTP request headers before actually entering the lambda handlers.
This can be summarized in something like this (preliminary auth steps):
def handler(event, context):
# preliminary auth steps - start
auth_header = event["headers"].get("Authorization")
if any([not auth_header, not is_auth_header_value_valid(auth_header)]):
return {
'statusCode': 401,
'body': json.dumps("Unauthorized access"),
'headers': {
'Content-Type': 'application/json',
},
}
# preliminary auth steps - end
try:
rsp = do_stuff()
status_code = 200
except Exception as e:
rsp = str(e)
status_code = 500
data = {
'statusCode': 200,
'body': json.dumps(rsp),
'headers': {
'Content-Type': 'application/json',
},
}
return data
But I don't want to repeat (copy and paste) that for every lambda handler. Coming from a Django background, I'm used to django middlewares when it comes to this kind of things, I'm wondering re how to do something similar here. Any suggestion?