微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

使用无服务器框架定义 lambda 授权方响应格式

如何解决使用无服务器框架定义 lambda 授权方响应格式

根据 to this AWS documentation page 涵盖 AWS API Gateway 的授权方,可以将授权方定义为 lambda 函数,在 isAuthorized 响应字段中返回布尔值以允许/拒绝 API 请求。

但是经过多次尝试后,我无法理解如何在 serverless.yml(或至少在 AWS 控制台中)中定义它

我是 AWS 和无服务器框架的新手。我决定暂时不深入研究 IAM 访问策略或 Cognito,因此我正在尝试构建一个非常简单的 lambda 授权器函数,该函数只产生一个布尔值来允许/拒绝 API 访问。

我在 functions 中定义了我的 serverless.yml 部分,如下所示:

functions:
  add_content:
    handler: src.handler.add
    module: src/handler
    events:
      - http:
          path: /content
          method: post
          authorizer: customAuthorizer
  customAuthorizer:
    handler: src.authorizer.authorize
    module: src/authorizer

授权人功能很简单:

def authorize(event,context):
    response = {"isAuthorized": True}
    return response

但是,如果我尝试对其进行测试,则会看到以下 CloudWatch 堆栈跟踪:

Mon May 03 20:06:11 UTC 2021 : Endpoint request body after transformations: {"type":"TOKEN","methodArn":"arn:aws:execute-api:eu-central-1:238758647165:ww9wzq8hp8/ESTestInvoke-stage/GET/","authorizationToken":"123456789"}
Mon May 03 20:06:11 UTC 2021 : Sending request to https://lambda.eu-central-1.amazonaws.com/2015-03-31/functions/arn:aws:lambda:eu-central-1:238758647165:function:sls-playground-dev-customAuthorizer/invocations
Mon May 03 20:06:11 UTC 2021 : Authorizer result body before parsing: {"isAuthorized": true}
Mon May 03 20:06:11 UTC 2021 : Execution Failed due to configuration error: Invalid JSON in response: Unrecognized field "isAuthorized",not marked as ignorable
Mon May 03 20:06:11 UTC 2021 : AuthorizerConfigurationException

除此之外:

  1. 在 AWS 控制台中打开 API 网关时,我没有文档中所示的 Develop 部分。
  2. 如果我尝试从 AWS 控制台手动创建验证器,则没有 response mode 部分。

enter image description here

解决方法

有两个可能的问题。

  1. REST API 的自定义授权方的响应不正确(这就是无服务器中的 http event)。 Output from an Amazon API Gateway Lambda authorizer 显示输出应该是什么样子,以及需要什么。
  2. 您打算使用 HTTP API。在这种情况下,您应该将 event 更改为 httpApiAnnouncing Support for AWS HTTP APIs

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。