Cognito用户池授权程序使用无服务器框架

问题描述 投票:11回答:3

我需要使用aws cognito userpool授权我的API端点。我可以手动完成,但我需要使用无服务器框架自动化授权部分。

无服务器框架是否支持aws cognito?

如果是这样,我们如何设置无服务器的aws-userpool?

amazon-web-services aws-lambda aws-api-gateway amazon-cognito serverless-framework
3个回答
22
投票

是的无服务器(v1.5)支持Cognito用户池授权程序。

如果您使用以前版本的无服务器,则必须更新v1.5或更高版本。

对于api端点的用户池授权,您必须指定pool arn。

functions:
  hello:
    handler: handler.hello
    events:
      - http:
          path: hello
          method: get
          integration: lambda
          authorizer:
            name: authorizer
            arn: arn:aws:cognito-idp:us-east-1:123456789:userpool/us-east-1_XXXXXX

更多细节阅读this文章。


15
投票

如果要将授权程序设置为您在资源中声明的Cognito用户池,则必须使用CloudFormation来创建授权程序。

functions:
  functionName:
    # ...
    events:
      - http:
          # ...
          authorizer: 
             type: COGNITO_USER_POOLS
             authorizerId: 
               Ref: ApiGatewayAuthorizer

resources:
  Resources:
    ApiGatewayAuthorizer: 
      Type: AWS::ApiGateway::Authorizer
      Properties: 
        Name: CognitoUserPool
        Type: COGNITO_USER_POOLS
        IdentitySource: method.request.header.Authorization
        RestApiId: 
          Ref: ApiGatewayRestApi
        ProviderARNs: 
          - Fn::GetAtt:
              - UserPool
              - Arn

    UserPool:
      Type: AWS::Cognito::UserPool

2
投票

无服务器1.35.1

万一有人偶然发现了我的做法。这是我的工作解决方案。

无论您在何处创建用户池,都可以继续添加ApiGatewayAuthorizer

# create a user pool as normal
CognitoUserPoolClient:
  Type: AWS::Cognito::UserPoolClient
  Properties:
    # Generate an app client name based on the stage
    ClientName: ${self:custom.stage}-user-pool-client
    UserPoolId:
      Ref: CognitoUserPool
   ExplicitAuthFlows:
   - ADMIN_NO_SRP_AUTH
   GenerateSecret: true

# then add an authorizer you can reference later
ApiGatewayAuthorizer:
  DependsOn:
  # this is pre-defined by serverless
  - ApiGatewayRestApi
  Type: AWS::ApiGateway::Authorizer
  Properties:
    Name: cognito_auth
    # apparently ApiGatewayRestApi is a global string
    RestApiId: { "Ref" : "ApiGatewayRestApi" }
    IdentitySource: method.request.header.Authorization
    Type: COGNITO_USER_POOLS
    ProviderARNs:
    - Fn::GetAtt: [CognitoUserPool, Arn]

然后在定义函数时

graphql:
  handler: src/app.graphqlHandler
  events:
  - http:
    path: /
    method: post
    cors: true
    integration: lambda
    # add this and just reference the authorizer
    authorizer:
      type: COGNITO_USER_POOLS
      authorizerId:
        Ref: ApiGatewayAuthorizer
© www.soinside.com 2019 - 2024. All rights reserved.