简体   繁体   English

AWS SAM CLI - Python - 授权中间件

[英]AWS SAM CLI - Python - authorization middleware

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.我正在开发我的第一个 AWS 无服务器 Python 应用程序,我需要一个在实际进入 lambda 处理程序之前处理和检查一些 HTTP 请求标头的东西。

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.但我不想为每个 lambda 处理程序重复(复制和粘贴)。 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.来自 Django 背景,当涉及到这类事情时,我习惯了 django 中间件,我想知道如何在这里做类似的事情。 Any suggestion?有什么建议吗?

There are two ways to achieve this.有两种方法可以实现这一点。

The first option is to us a API Gateway Lambda authorizer .第一个选项是给我们一个API 网关 Lambda 授权方 But this requires using an API Gateway.但这需要使用 API 网关。 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.有一些事情可以开箱即用,或者您可以提供自定义授权器 Lambda,您必须自己构建。 This Lambda can do whatever you want to authorize an incoming request.这个 Lambda 可以做任何你想做的事情来授权传入的请求。 This is effectively the same as a Django Middleware.这实际上与 Django 中间件相同。

The second option are Lambda Layers .第二个选项Lambda 层 You can use those to share common code between Lambda functions.您可以使用它们在 Lambda 函数之间共享公共代码。 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.您可以使用上面的代码创建一个包含授权方法的 Lambda 层,然后将此层附加到所有需要它的 Lambda。 Maybe this blog article helps .也许这篇博客文章有帮助

Personally, I think the API Authorizers are the better option for production.就个人而言,我认为 API 授权器是生产的更好选择。 We use them quite a lot.我们经常使用它们。 But they add complexity and cost.但它们增加了复杂性和成本。 Lambda layers are probably fine for smaller projects. Lambda 层可能适用于较小的项目。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM