Cognito user pool authorizer With Serverless Framework

后端 未结 3 1169
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-31 00:42

I need to authorize my API end point using aws cognito userpool. I can do it manually, but I need to automate the authorization part with the serverless framework.

3条回答
  •  温柔的废话
    2020-12-31 01:36

    Serverless 1.35.1

    In case someone stumbles across this how I did. Here is my working solution.

    Wherever you create the user pool, you can go ahead and add 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]
    

    Then when you define your functions

    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
    

提交回复
热议问题