Authorization in TypeGraphQL with permission layer like GraphQL Shield.
I often use TypeGraphQL + Prisma + typegraphql-prisma for backend applications. Firstly, all the goodness of GraphQL on Node.js, and then adding complete TypeScript support makes this combo unbeatable! The integration is just that good. I get all the CRUD resolvers and schema types ahead of time so I can build custom resolvers a lot faster than if I was just building my own resolvers, and managing my own database schema separately.
Check this link if you want to know what I mean: https://typegraphql.com/docs/prisma.html
Now, this article is going to be useful if you already know what we are going to be working with here: TypeGraphQL and looking at implementing authorization for your API.
Coming to the topic of Authorization
My GraphQL APIs often need authorization. TypeGraphQL allows role-based authorization out-of-the-box. So if I had “ADMIN” type users and “USER” type users, I could easily write an Authorized(“ADMIN”) to authorize only admins to access certain resolvers.
But let’s take a little more complex scenario, however a bit vague. Let's say I have a social media application and I want users to be able to only edit posts created by them. Further, I want users to be able to comment on some posts but not on others. How do we define roles for such scenarios? I find it hard to implement a logical way.
Instead, years back, I used to implement a permission layer of rules for such use-cases in graphql shield. I can define reusable roles such as isAuthenticated, or isAuthor, or isAllowedToComment etc to determine permissions for each user. Moreover, I can combine multiple of these rules using boolean logic such as (Rule A OR Rule B) AND Rule C. That is complex to do with what TypeGraphQL, or so it seems to me at least.
The solution to this complexity
typegraphql-authchecker. I love using TypeGraphQL and Prisma. So I decided that I wanted a permissions layer for authorization in the framework. And the package delivers those little functionalities to make that happen. I can chain rules, implement boolean logic on them and more (check the project link for the documentation). Of course, it is probably not stable and I have not spent enough time on it. But that is why I put it out here, in the open so I can have your help to make it complete.
Hope that you found this useful! Find me on Twitter if you have any comments about this article, or anything else.
I have also been working on Deploifai that is a modern cloud platform for data and AI. Check it out if you work with things like Jupyter/TensorFlow/PyTorch on the cloud.
Thanks a lot for reading!