如何在无服务器中创建 API-网关授权方的资源

How to create a resourse of API-Gatway authorizer, in serverless

我在我的 API 中使用 cognito 授权器,并使用无服务器配置 api。为了向函数添加自动调整器,我找到了这段代码 ():

teste:
  handler: handler.teste
  memorySize: 128
  events:
    - http:
        path: teste
        method: get
        authorizer:
          name: api-authorizer
          arn: arn:aws:cognito-idp:XXXXXXXXX:XXXXXXXXXX:userpool/XXXXXXX_XXXXXXX
          type: token

这段代码工作得很好,但我需要在多个函数中重复同一个授权者,并使用这段代码,为每个函数创建一个新的授权者....这是一种资源浪费,并且在AWS 控制台

为了解决这个问题,我尝试这样做:

teste:
  handler: handler.teste
  memorySize: 128
  events:
    - http:
        path: teste
        method: get
        authorizer: myAuthorizer


resources:
  Resources:
    myAuthorizer:
      Type: AWS::ApiGateway::Authorizer
      Properties:
        Name: "testing"
        arn: arn:aws:cognito-idp:XXXXXXXXX:XXXXXXXXXX:userpool/XXXXXXX_XXXXXXX
        authorizerId:
          Ref: api-authorizer

但是没有成功,我没有找到这方面的文档或指南。

您正在寻找的是某种类型的 API 网关授权器,一个 Cognito Authorizer。这些专门用于对来自 Cognito 用户池的用户进行身份验证。

要将 Cognito 授权器与 serverless 一起使用,您的 serverless.yml 可能如下所示:

teste:
  handler: handler.teste
  memorySize: 128
  events:
    - http:
        path: teste
        method: get
        authorizer:
          arn: arn:aws:cognito-idp:XXXXXXXXX:XXXXXXXXXX:userpool/XXXXXXX_XXXXXXX

使用 Cogntio 授权方时,您不需要发送授权方名称或类型。此外,arn 应该指向您的 Cognito 用户池,您的示例中的那个似乎是。

如果您需要更多信息或示例,请查看 custom authorizers 上的无服务器文档主题。

在我看来,重复授权人部分没什么大不了的。在我的例子中,重复它是有意义的,因为我们使用的是范围。

listItems:
  handler: handler.listItems
  events:
    - http:
        method: get
        path: /list-items
        authorizer:
          arn: ${self:custom.vars.${self:custom.vars.stage}.userPoolArn}
          scopes:
            - transactions/read              

writeItem:
  handler: handler.writeItem
  events:
    - http:
        method: post
        path: /write-item
        authorizer:
          arn: ${self:custom.vars.${self:custom.vars.stage}.userPoolArn}
          scopes:
            - transactions/write

但是如果你想分享一个授权人,它就在这里。

resources:
  Resources:
    ApiGatewayAuthorizer:
      Type: AWS::ApiGateway::Authorizer
      Properties:
        AuthorizerResultTtlInSeconds: 300
        IdentitySource: method.request.header.Authorization
        Name: Cognito
        RestApiId:
          Ref: YourApiGatewayName
        Type: COGNITO_USER_POOLS
        ProviderARNs:
          - arn:aws:cognito-idp:${self:provider.region}:xxxxxx:userpool/abcdef

functions:
  deleteUser:
      ...
    events:
      - http:
          path: /users/{userId}
          ...
          # Provide both type and authorizerId
          type: COGNITO_USER_POOLS # TOKEN or REQUEST or COGNITO_USER_POOLS, same as AWS Cloudformation documentation
          authorizerId:
            Ref: ApiGatewayAuthorizer # or hard-code Authorizer ID

参考: https://serverless.com/framework/docs/providers/aws/events/apigateway/#share-authorizer