使用无服务器,如何将 Lambda 函数的授权者设置为资源中的 Cognito 用户池?

Res*_*ign 5 yaml amazon-web-services aws-lambda serverless-framework serverless

在我的 serverless.yml 中,我有一个 Lambda 函数,我想将其授权者设置为我在下面的资源部分中声明的 Cognito 用户池。我见过设置授权者的示例,aws_iam但这似乎是错误的。任何帮助都会很棒:)

我想我需要将授权者的 ARN 设置为池的 ARN,但如何获取它?或者说这是正确的吗?

Mik*_*ick 3

正如另一个答案中所述,对 ARN 进行硬编码是有效的。直觉上,你可能会认为这样的事情会起作用:

    authorizer:
      arn: 
        Fn::GetAtt: [UserPool, Arn]
Run Code Online (Sandbox Code Playgroud)

遗憾的是,事实并非如此。看起来Serverless会让您arn遇到几个正则表达式,以确定您指向的是 lambda 还是用户池。Ref这种方法似乎与使用诸如、Fn::Join、 或 之类的方法不能很好地配合Fn::GetAtt


Serverless 1.27.3(自提出此问题后发布)开始,有一种可用的解决方法

本质上,您在您的部分中声明您的授权者resources,而不是让无服务器自动为您创建它。authorizerId然后,您在您的部分中使用新密钥functions来指向该授权者。一个最小的例子:

service: sls-cognitotest

provider:
  name: aws
  runtime: nodejs6.10
functions:
  hello:
    handler: handler.hello
    events:
      - http:
          method: any
          path: /api/{proxy+}
          integration: lambda
          authorizer: 
            type: COGNITO_USER_POOLS
            authorizerId: { Ref: MyApiGatewayAuthorizer }
resources:
  Resources:
    CognitoUserPoolGeneral:
      Type: AWS::Cognito::UserPool
      Properties:
        UserPoolName: general
    MyApiGatewayAuthorizer: 
      Type: AWS::ApiGateway::Authorizer
      Properties: 
        AuthorizerResultTtlInSeconds: 10
        IdentitySource: method.request.header.Authorization
        Name: MyCognitoAuthorizer
        RestApiId: 
          Ref: ApiGatewayRestApi
        Type: COGNITO_USER_POOLS
        ProviderARNs: 
          - {"Fn::Join": ["", ["arn:aws:cognito-idp:", {Ref: "AWS::Region"}, ":", {Ref: "AWS::AccountId"}, ":userpool/", Ref: CognitoUserPoolGeneral]]} 
Run Code Online (Sandbox Code Playgroud)

这不是很好,但比必须将用户池 ARN 硬编码到模板中要好。