0

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?

Luke
  • 1,794
  • 10
  • 43
  • 70

1 Answers1

1

There are two ways to achieve this.

The first option is to us a API Gateway Lambda authorizer. But this requires using an API Gateway. There are a few things that those can do out of the box or you could provide a custom authorizer Lambda, that you have to build yourself. This Lambda can do whatever you want to authorize an incoming request. This is effectively the same as a Django Middleware.

The second option are Lambda Layers. You can use those to share common code between Lambda functions. You could create a Lambda Layer that contains a authorization method with your code from above and then attach this Layer to all the Lambdas that need this. Maybe this blog article helps.

Personally, I think the API Authorizers are the better option for production. We use them quite a lot. But they add complexity and cost. Lambda layers are probably fine for smaller projects.

Jens
  • 20,533
  • 11
  • 60
  • 86