Reputation: 831
I'm trying to define API Gateway resources using CloudFormation. Specifically, I'm attempting to create a template for an API Gateway Resource Method that authenticates using Cognito. I've created the Authorizer, and using the console I can perform this configuration without issue (see image attached). I just can't find a way to specify the API method request authorization using the Cognito user pool. It's driving me crazy. As far as I can see, no documentation covers this.
Does anyone know if this is possible, and if so, how to do it? I realize I can achieve this using Swagger but I'm not looking forward to re-defining all of my API Gateway resources in Swagger vs. CloudFormation.
Thanks in advance!
Upvotes: 3
Views: 7754
Reputation: 1342
If you are using SAM then you set the pool as a global default and mark the functions you don't want to be authenticated.
MyApi:
Type: AWS::Serverless::Api
Properties:
StageName: Prod
Cors: "'*'"
Auth:
DefaultAuthorizer: MyCognitoAuthorizer
Authorizers:
MyCognitoAuthorizer:
UserPoolArn: !GetAtt MyCognitoUserPool.Arn
MyFunction:
Type: AWS::Serverless::Function
Properties:
CodeUri: ./src
Handler: lambda.handler
Runtime: nodejs8.10
Events:
Root:
Type: Api
Properties:
RestApiId: !Ref MyApi
Path: /
Method: GET
MyCognitoUserPool:
Type: AWS::Cognito::UserPool
Properties:
UserPoolName: !Ref CognitoUserPoolName
Policies:
PasswordPolicy:
MinimumLength: 8
UsernameAttributes:
- email
Schema:
- AttributeDataType: String
Name: email
Required: false
MyCognitoUserPoolClient:
Type: AWS::Cognito::UserPoolClient
Properties:
UserPoolId: !Ref MyCognitoUserPool
ClientName: !Ref CognitoUserPoolClientName
GenerateSecret: false
For functions you don't want to be behind cognito. Define in the events section of the AWS::Serverless::Function definition.
Events:
Root:
Type: Api
Properties:
RestApiId: !Ref MyApi
Path: /
Method: GET
Auth:
Authorizer: 'NONE'
Use the AWS Sam template documentation rather than the cloudformation definitions.
Upvotes: 5
Reputation: 4152
I don't have a code sample handy, but here's what you will need to do:
1) Add an Authorizer resource to your template with type "COGNITO_USER_POOLS",
2) Set the authorizerId on the API method resource to the ID reference from the authorizer. Set the authorizationType on the method to "COGNITO_USER_POOLS"
As for the user pools themselves, you will need to use custom resources, at least until official support is released. There are several open-source implementations out there that you could use (here's one example: https://github.com/aws-samples/aws-api-gateway-developer-portal/tree/7d0d1e56d54e9775ee2d18907ebdf1db9dafcc06/lambdas/cognito-cloudformation-custom-resource)
Upvotes: 3