GraphQL Shield — permission framework for authorisation systems

Santhosh Kumar
2 min readJan 18, 2023

--

Implement your server permission in a clear and deterministic way and let it do the rest. Yes, GraphQL Shield lets you guard your schema in a simple, clear and efficient way.

GraphQL Shield is a GraphQL library, that helps you create a permission layer for your server. The shield engine on every request checks for the permission definition, handles error better and no internal data will be exposed.

Start adding GraphQL Shield to your server

Let’s pick a real world example to understand how GraphQL Shield works. You can clone the boiler plate of Apollo 4,

Schema:

A server with list of books as its data
A Schema defnition for the books and Resolver to retrieve the books

Above Query allows you to fetch the list of books available. Let’s bring the Shield in to action.

Now, the shield allows the query books to retrieve the information. Let’s define a rule to check for the presence of token in the context and return boolean response.

Now, every time a query to books, will be executed and if the rule results in

  • true: then the query is executed
  • false: then Unauthorised error is thrown

Add the permission to the schema of the server.

When a request hits the server, context will set the token based on the headers and the permissions will check for the presence of token on context and decide on the access to the operation (query or mutation)

Per Type Wildcard Rule or Fallback

There is an option to specify a rule that will be applied to all fields of a type (Query Mutation).

  • books — executed a rule isAllowedToReadBooks
  • articles — allowed without any condition check
  • any other query — is denied

allow & deny are the predefined shield rules.

Logic Rules — Combine rules

  • and — allows access only if all sub rules used return true
  • chain — rule allows you to chain the rules, meaning that rules won’t be executed all at once, but one by one until one fails or all pass
  • or — resolves to true if at least one rule passes
  • race — rule allows you to chain the rules so that execution stops once one of them returns

Custom Errors

Shield, by default, catches all errors thrown during resolver execution. This way we can be 100% sure none of your internal logic can be exposed to the client if it was not meant to be. Please find the examples below.

--

--

Santhosh Kumar

I am passionate about Transforming ideas into software products and deliver it global.