Authorization Rules in GraphQL and AWS Amplify

06/05/20191 Min Read — In DevOps, JavaScript

AWS Amplify provides a back-end service for your front-end or mobile app. It also offers build-in UI components and functions to integrate with their AWS services.

It integrates well with JavaScript and offers a GraphQL endpoint.

Additionally, AWS Amplify ships with an Authentication API.

How can you allow users to read all data (see everything), but restrict their ability to modify data?

For example, my GraphQL schema has a Product type:

type Product @model @auth(rules: [{ allow: owner, identityField: "sub" }]) {
id: ID!
description: String!
market: Market @connection(name: "MarketProducts")
file: S3Object!
price: Float!
shipped: Boolean!
owner: String
createdAt: String
}

As you can see, the @auth directive defines that only the owner of a product can create, read, modify or delete a product.

Unfortunately, other users of the app can't even read a product. So they won't see it in the app.

There is an open GitHub issue that addresses this problem.

For now, a workaround exists:

Subscribing everyone to the "Everyone" group will do the trick. You can also specify that the "Admin" rule should only apply to create, update, and delete operations.

@auth(rules: [
{ allow: groups, groups: ["Admin"], operations: [create, update, delete]}
])

Having an allow: authenticated will become necessary when and/or rules or strict mode are introduced to @auth.

Let's apply this to our schema.graphql:

type Product
@model
@auth(
rules: [
{
allow: owner
identityField: "sub"
operations: [create, update, delete]
}
]
) {
id: ID!
description: String!
market: Market @connection(name: "MarketProducts")
file: S3Object!
price: Float!
shipped: Boolean!
owner: String
createdAt: String
}

Now, everyone can see all products, but only product owners can create, update or delete products.

Further Reading