GraphQL shield for authorization
Shield is an easy way to add authorization on GraphQL. It’s a library that helps you create a permission layer for your server. e.g Let’s suppose you need to create a layer where you want your APIs to be secured from unauthorized access i.e who is accessing what?
Authorization plays an important part in any website and in one way or another, one needs to implement authorization to prevent protected/forbidden pages from public view.
Ways to add authorization in your GraphQL:
- In all resolvers
You can add permissions in each and every resolver and can respond according to that. But it won’t be a convenient way and will be against the DRY principles.
Permissions are with every resolver and every resolver is accountable for handling authorization.
- Using GrapghQL Shield
GraphQL shield is a library that provides a way to set permissions at the server level and throws an error if permissions are not met for the current user.
In this blog, I will be writing about how to use GraphQL shields. So let’s get started.
Install
npm install graphql-shield
Set up permissions
I have defined two permissions currently in the file above
- isAuthenticated — checks whether the user is logged in or not
- isAdmin — checks whether the user is admin or not depending on the role. You can define more such permissions like isPublisher, isSuperAdmin, canUpdate, etc…
Create a middleware
shield accepts an object where we can define the permissions applicable on the different schema levels. Here user's schema query will only be visible to the user who is authenticated else it will throw an error. Like this, you can define more permissions and can authorize different schema based on the role of the user.
You can also merge two permissions. Read more about the rules here
That’s it for this blog. If you have anything to ask, put it in the comments section and if you like this blog, don’t forget to hit the clap icon and follow me for more such blogs.
Drink water. Keep smiling…