Add Cognito Groups to Amplify Cloudformation templates

2 minute read

If you have read any of my previous articles you will know how much I love AWS Amplify. The devX (developer experience) is second to none.

As I have shown before, it is super easy to get a full-stack serverless application up and running in a matter of keystrokes.

Need authentication? Simply run amplify add auth

Need a GraphQL API? Easy amplify add api

What about adding authentication to your api? Amplify provides a set of @directives that allow you to restrict who can access what.

In the example above we are restricting access to the posts by the user that created the post in the first place. This is done by the magic marriage of Cognito and the API.

Groups

Cognito also allows you to create groups and then add users to those groups. This allows you to easily add a collection of permissions to a group and this will filter down to the users of that group. This is really useful for apply blanket apply access rules to the data in your database.

I will use the example from the Amplify documentation. The example uses a draft entity. You want to allow the Draft’s owner to create, update, delete, and read Draft objects. However, you also want the Draft’s editors to be able to update and read Draft objects. Finally you want users that are members of the Admin group to be able to do everything. This would be represented in your schema like this:

Create groups

As I mentioned above Cognito groups allow us to easily control permissions on a large number of users. Cognito groups can be created in the AWS console but this poses a problem. You are not creating this in code and so it cannot be put in to version control. Also when you add / update your Amplify stack these groups are probably going to be overwritten.

The solution to this is to get Cloudformation to create the groups for you when you are making any updates to your Amplify application.

This can be done by editing the Cloudformation templates that are generated by Amplify. But you need to be care which ones you update as some are auto grenerated when ever you use the Amplify CLI.

The file you need to edit will be at a path similar to this: [projectname]/amplify/backend/auth/[appname]/[appname]-cloudformation-template.yml

You need to add the following code, tailored to your needs:

The above code creates two Cognito groups, Admins and Users. Once you have deployed these changes they can be used throughout you applications, and in our example above the Admin group can now perform all operations on the draft entity.

In conclusion:

We have discussed the flexibility of Cognito groups and the power of Cloudformation in allowing repeatable, version controlled stack generation.