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

nus*_*ajy 14 amazon-web-services amazon-cognito aws-lambda aws-api-gateway serverless-framework

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

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

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

Nir*_*thi 23

是的 无服务器(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
Run Code Online (Sandbox Code Playgroud)

更多详细信息阅读文章.

  • @NiroshanRanapathi如何将授权者设置为您在serverless.yml的参考资料部分中声明的Cognito用户池? (2认同)

Deh*_*hli 17

如果要将授权程序设置为您在资源中声明的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
Run Code Online (Sandbox Code Playgroud)


sev*_*ens 7

无服务器 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]
Run Code Online (Sandbox Code Playgroud)

然后当你定义你的函数时

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
Run Code Online (Sandbox Code Playgroud)