Today I’ve added local overrides to the global variables in my template.yml file. This was pretty finicky – a lot of conflicting suggestions out there unfortunately. These are the settings that ended up working for me.
I’ve spent today implementing Cognito with AWS SAM and it took quite a while to work out what needed to be done – unfortunately there’s a lot of conflicting doco out there. Posting a sample template just in case it’s able to help anyone else out.
The first thing to do is to explicitly define you rest API. By default AWS SAM will generate one with a default logical id of ServerlessRestApi. You’ll need to override this:
# See links for more info
# Referencing cognito authorizer: https://github.com/awslabs/serverless-application-model/issues/512#issuecomment-411284092
# Logical id is auto generated: https://github.com/awslabs/serverless-application-model/blob/master/docs/internals/generated_resources.rst#api
# Sample template.yml: https://github.com/awslabs/serverless-application-model/blob/release/v1.8.0/examples/2016-10-31/api_cognito_auth/template.yaml
Auth: # We will eventually define other auth options here such as Usage Plans/Api Keys, AWS_IAM, and Resource Policies
UserPoolArn: !GetAtt MyCustomCognitoUserPool.Arn # Can be a string, or array
# Identity: # Optional
# Header: ... # Optional; Default: Authorization
# ValidationExpression: ... # Optional; ensures the request header matches a pattern before checking in with the Authorizer endpoint; is there a default we can set for Cognito User Pools Auth?
You’ll also need to create a user pool and client:
You then add the api id and the auth attribute to each of your function properties. If you’ve used the default authorizer property when defining the associated api you can override it by using authorizer: none.
I ran into a bit of an issue after deleting a DynamoDb table via the AWS Console that had been created via CloudFormation (using AWS SAM). After deleting it I had expected it to be re-created automatically on the next deploy. Unfortunately this didn’t happen.
To fix it, I removed all references to the table from my template.yml file (this includes the table definition and any !Ref tags). After pushing this changeset I returned all of the references and re-pushed.