Authorization Patterns in GraphQL

Rate this content
Bookmark

As it says in the GraphQL documentation: "Delegate authorization logic to the business logic layer". Is that really everything you need to know? This advice is coming from a good place, but it relies on you knowing how you would go about doing authorization in the first place — and this isn't a widely solved problem! On top of that, many of the approaches used in traditional applications don't quite carry over. In this talk, you'll get a crash course in authorization and how to implement it for GraphQL APIs."

FAQ

Authentication is about verifying identity, typically using methods like usernames and passwords, single sign-on, or two-factor authentication. Authorization, on the other hand, determines what authenticated users are permitted to do within an application, such as accessing specific resources or performing actions.

GitHub uses a robust authorization system that allows roles at the organizational level, such as owner and member, with specific permissions like creating repositories. It also allows more granular control by enabling users to invite collaborators to repositories with different access levels.

The business logic layer in application architecture refers to the part of the backend that handles the processing of data from client requests, performing operations like data gathering, computations, and transformations necessary to fulfill those requests.

Centralizing authorization logic helps ensure consistency across different parts of an application, reduces duplication of logic, and simplifies maintenance. It prevents discrepancies in permissions across various APIs, which can lead to security vulnerabilities and inconsistent user experiences.

A recommended pattern for GraphQL authorization is to delegate it to the business logic layer rather than handling it at the resolver level. This approach avoids duplicating authorization logic for different APIs and ensures consistent enforcement of access controls across the application.

Implementing authorization at the GraphQL resolver level can simplify development for teams primarily using GraphQL. It allows for cleaner and more direct integration of authorization checks within GraphQL operations, potentially enhancing control and visibility over access permissions.

GraphQL types can be extended with a permissions field that contains all the permissions the current user has on a particular resource. This allows the UI to conditionally render elements based on these permissions, enhancing the user interface by dynamically adjusting available actions based on user permissions.

Sam Scott
Sam Scott
20 min
08 Dec, 2022

Comments

Sign in or register to post your comment.

Video Summary and Transcription

This talk introduces the theory and practice of authorization in GraphQL, highlighting the importance of proper authorization in ensuring application functionality and security. Delegating authorization to the business logic layer is a golden rule in GraphQL, ensuring consistency and avoiding duplication of logic. Authorization can be done in the resolver layer, but it is recommended to combine it with filtering at the database level. Abstracting authorization behind an API centralizes logic and makes it easier to manage. Custom directives and permissions fields can reduce the tedium of ensuring correct authorization in every resolver.

1. Introduction to Authorization in GraphQL

Short description:

This talk introduces the theory and practice of authorization in GraphQL. The speaker provides definitions of authentication and authorization, emphasizing the importance of application authorization. They give examples of robust authorization systems in GitHub and AWS IAM, as well as less obvious examples like Google Docs and Notion. The talk highlights the significance of proper authorization in ensuring the functionality and security of an application.

All good talks need to start with a quote, right? So, you know how they say, in theory, there's no difference between theory and practice, but in practice there is? Well, that's what this talk is about. I'm going to talk to you about the theory of authorization in GraphQL, and then if and how this matches practice. So, I'm Sam, I'm the cofounder and CTO at Oso, and we build authorization for developers. And as someone who did a PhD in cryptography and sort of gradually slid more and more into the practical world, I'm pretty familiar with the distinction between theory and practice.

So, strap yourselves in and learn a little about patterns in GraphQL, both theoretical and practical. So, I know there's a lot of confusion out there around the difference between authentication and authorization, so I'll start out with a few definitions. Authentication is all about identity, you know, who is the user? It may be you identify them through username and password, you may do single sign on, you may have two-factor authentication, that's all authentication. Authorization is the piece that comes next. Now that you know who the user is, what can they do? And I'm going to be talking about application authorization. So, specifically, what can they do inside your application?

To give you a few examples, GitHub, this is a great example. It's got a pretty robust authorization system. It allows you to do roles at the organizational level, like owner and member, and which of those can create repositories. You can also have roles at a more granular level. I can invite you as a collaborator to my repository and give you a role that grants you different access. Now, I really like GitHub as an example, because they also have a GraphQL API, so we'll be able to see not just authorization generically, but also in the context of GraphQL. For a bit more of a complex authorization example, take AWS IAM. And with AWS IAM, you can sort of write your own authorization, logic, and policies to determine who is allowed to do what inside of this ginormous platform. It's a pretty complex one. But there are some application authorization that you might not think about so much. Take something like Google Docs or Notion, where part of the core workflow is inviting people to collaborate on documents, or maybe invite them to an entire folder and say where they can view, edit or comment on those documents. That's all authorization. GitHub, AWS, Google Docs, Notion, these are all fantastic examples of application authorization.

So before we start getting into the technical details, why is this an important topic to talk about? Well, first of all, if you don't have authorization and application, your product is entirely broken. You sort of have anarchy. Anybody can go in and do anything. They can go and delete other users, they can delete other people's data, they can do anything. But on the other hand, if your authorization is broken, people can't get access to anything. Your app doesn't work. If your authorization is buggy, then users start getting annoyed. We've all been in that situation where the authorization logic in an app is so broken and frustrating that you just say, you know what, I'm going to go make everybody an admin.

2. Authorization Patterns in the Business Logic Layer

Short description:

The first pattern discussed is authorization in the business logic layer. Delegating authorization to the business logic layer is a golden rule in GraphQL. The business logic layer handles mapping client requests to the application's internal processes. It gathers relevant data, computes fields, and performs transformations. The persistence layer, on the other hand, deals with reading and writing data to the database.

I don't want to deal with this permission system. So that can be what the implications are of doing authorization wrong or even just poorly.

Okay, so getting into the authorization patterns. The first pattern I want to talk about is authorization in the business logic layer. Now, if you're like me, and you're coming to a new topic, probably the first thing you do is just go ahead and Google it. Now you type in GraphQL authorization. The first hit happens to be GraphQL.org. It has this beautiful conceptual overview on authorization in GraphQL. And it starts with this one kind of golden rule. It says, delegate authorization to the business logic layer. Now, there's potentially two new concepts in this that you haven't thought about before. One, what does it mean to delegate authorization? And two, what is this business logic layer? So the term business logic layer also comes from another GraphQL.org page. This page is around thinking in graphs. And it sort of lays out this kind of like architectural diagram of layers of how to think about where GraphQL fits into your application. I have my own version of this diagram so that I can kind of doodle on it and draw things. And, okay, so when I spoke about the layers of your application, what I'm really talking about is a backend application, right? So kind of putting this picture into context, it maybe looks more like this. So first of all, on the left, you maybe have your client. This could be a web browser, this could be a mobile app. And those things are all gonna be making, you know, various requests to your backend, to your backend APIs. Those could be rest requests, those could be GraphQL queries. So the business logic layer, this sort of, this handles that, like, the, you know, mapping those requests to actual things that are going inside your application. For example, if you want to get a specific organization, the business logic would be gathering all the relevant data to return, computing fields, doing transformations, things like that.

Now the bottom, the persistence layer, this is what's like reading and writing data to the database. Okay, for example, coming back to that, user wants to review a specific organization, right, so maybe they do that through a rest request, and in the back end maybe we have some application logic that we wrote to handle that, you know, looks up the organization by that ID from the database. It authorizes, is the user allowed to read that organization, and if not, returns null. Okay, so that's maybe our rest endpoint. Similarly, on the GraphQL side, you know, we now instead have a query for an organization by a specific ID. But again, we write our resolver logic to say, first, you know, look up that organization by that particular ID, authorize, is the user allowed to read that organization and similarly return null. Okay. So far, so good.

Check out more articles and videos

We constantly think of articles and videos that might spark Git people interest / skill us up or help building a stellar career

Routing in React 18 and Beyond
React Summit 2022React Summit 2022
20 min
Routing in React 18 and Beyond
Top Content
Concurrent React and Server Components are changing the way we think about routing, rendering, and fetching in web applications. Next.js recently shared part of its vision to help developers adopt these new React features and take advantage of the benefits they unlock.In this talk, we’ll explore the past, present and future of routing in front-end applications and discuss how new features in React and Next.js can help us architect more performant and feature-rich applications.
From GraphQL Zero to GraphQL Hero with RedwoodJS
GraphQL Galaxy 2021GraphQL Galaxy 2021
32 min
From GraphQL Zero to GraphQL Hero with RedwoodJS
Top Content
We all love GraphQL, but it can be daunting to get a server up and running and keep your code organized, maintainable, and testable over the long term. No more! Come watch as I go from an empty directory to a fully fledged GraphQL API in minutes flat. Plus, see how easy it is to use and create directives to clean up your code even more. You're gonna love GraphQL even more once you make things Redwood Easy!
Local State and Server Cache: Finding a Balance
Vue.js London Live 2021Vue.js London Live 2021
24 min
Local State and Server Cache: Finding a Balance
Top Content
How many times did you implement the same flow in your application: check, if data is already fetched from the server, if yes - render the data, if not - fetch this data and then render it? I think I've done it more than ten times myself and I've seen the question about this flow more than fifty times. Unfortunately, our go-to state management library, Vuex, doesn't provide any solution for this.For GraphQL-based application, there was an alternative to use Apollo client that provided tools for working with the cache. But what if you use REST? Luckily, now we have a Vue alternative to a react-query library that provides a nice solution for working with server cache. In this talk, I will explain the distinction between local application state and local server cache and do some live coding to show how to work with the latter.
Batteries Included Reimagined - The Revival of GraphQL Yoga
GraphQL Galaxy 2021GraphQL Galaxy 2021
33 min
Batteries Included Reimagined - The Revival of GraphQL Yoga
The Guild has recently released Envelop - a new, modern GraphQL Server Framework and plugin system. In this talk I’ll share a brief overview of Envelop and why you should probably upgrade your existing GraphQL server to it.
Rock Solid React and GraphQL Apps for People in a Hurry
GraphQL Galaxy 2022GraphQL Galaxy 2022
29 min
Rock Solid React and GraphQL Apps for People in a Hurry
In this talk, we'll look at some of the modern options for building a full-stack React and GraphQL app with strong conventions and how this can be of enormous benefit to you and your team. We'll focus specifically on RedwoodJS, a full stack React framework that is often called 'Ruby on Rails for React'.

Workshops on related topic

Build with SvelteKit and GraphQL
GraphQL Galaxy 2021GraphQL Galaxy 2021
140 min
Build with SvelteKit and GraphQL
Top Content
Featured WorkshopFree
Scott Spence
Scott Spence
Have you ever thought about building something that doesn't require a lot of boilerplate with a tiny bundle size? In this workshop, Scott Spence will go from hello world to covering routing and using endpoints in SvelteKit. You'll set up a backend GraphQL API then use GraphQL queries with SvelteKit to display the GraphQL API data. You'll build a fast secure project that uses SvelteKit's features, then deploy it as a fully static site. This course is for the Svelte curious who haven't had extensive experience with SvelteKit and want a deeper understanding of how to use it in practical applications.

Table of contents:
- Kick-off and Svelte introduction
- Initialise frontend project
- Tour of the SvelteKit skeleton project
- Configure backend project
- Query Data with GraphQL
- Fetching data to the frontend with GraphQL
- Styling
- Svelte directives
- Routing in SvelteKit
- Endpoints in SvelteKit
- Deploying to Netlify
- Navigation
- Mutations in GraphCMS
- Sending GraphQL Mutations via SvelteKit
- Q&A
End-To-End Type Safety with React, GraphQL & Prisma
React Advanced Conference 2022React Advanced Conference 2022
95 min
End-To-End Type Safety with React, GraphQL & Prisma
Featured WorkshopFree
Sabin Adams
Sabin Adams
In this workshop, you will get a first-hand look at what end-to-end type safety is and why it is important. To accomplish this, you’ll be building a GraphQL API using modern, relevant tools which will be consumed by a React client.
Prerequisites: - Node.js installed on your machine (12.2.X / 14.X)- It is recommended (but not required) to use VS Code for the practical tasks- An IDE installed (VSCode recommended)- (Good to have)*A basic understanding of Node.js, React, and TypeScript
GraphQL for React Developers
GraphQL Galaxy 2022GraphQL Galaxy 2022
112 min
GraphQL for React Developers
Featured Workshop
Roy Derks
Roy Derks
There are many advantages to using GraphQL as a datasource for frontend development, compared to REST APIs. We developers in example need to write a lot of imperative code to retrieve data to display in our applications and handle state. With GraphQL you cannot only decrease the amount of code needed around data fetching and state-management you'll also get increased flexibility, better performance and most of all an improved developer experience. In this workshop you'll learn how GraphQL can improve your work as a frontend developer and how to handle GraphQL in your frontend React application.
Build a Headless WordPress App with Next.js and WPGraphQL
React Summit 2022React Summit 2022
173 min
Build a Headless WordPress App with Next.js and WPGraphQL
Top Content
WorkshopFree
Kellen Mace
Kellen Mace
In this workshop, you’ll learn how to build a Next.js app that uses Apollo Client to fetch data from a headless WordPress backend and use it to render the pages of your app. You’ll learn when you should consider a headless WordPress architecture, how to turn a WordPress backend into a GraphQL server, how to compose queries using the GraphiQL IDE, how to colocate GraphQL fragments with your components, and more.
Relational Database Modeling for GraphQL
GraphQL Galaxy 2020GraphQL Galaxy 2020
106 min
Relational Database Modeling for GraphQL
Top Content
WorkshopFree
Adron Hall
Adron Hall
In this workshop we'll dig deeper into data modeling. We'll start with a discussion about various database types and how they map to GraphQL. Once that groundwork is laid out, the focus will shift to specific types of databases and how to build data models that work best for GraphQL within various scenarios.
Table of contentsPart 1 - Hour 1      a. Relational Database Data Modeling      b. Comparing Relational and NoSQL Databases      c. GraphQL with the Database in mindPart 2 - Hour 2      a. Designing Relational Data Models      b. Relationship, Building MultijoinsTables      c. GraphQL & Relational Data Modeling Query Complexities
Prerequisites      a. Data modeling tool. The trainer will be using dbdiagram      b. Postgres, albeit no need to install this locally, as I'll be using a Postgres Dicker image, from Docker Hub for all examples      c. Hasura
Building GraphQL APIs on top of Ethereum with The Graph
GraphQL Galaxy 2021GraphQL Galaxy 2021
48 min
Building GraphQL APIs on top of Ethereum with The Graph
WorkshopFree
Nader Dabit
Nader Dabit
The Graph is an indexing protocol for querying networks like Ethereum, IPFS, and other blockchains. Anyone can build and publish open APIs, called subgraphs, making data easily accessible.

In this workshop you’ll learn how to build a subgraph that indexes NFT blockchain data from the Foundation smart contract. We’ll deploy the API, and learn how to perform queries to retrieve data using various types of data access patterns, implementing filters and sorting.

By the end of the workshop, you should understand how to build and deploy performant APIs to The Graph to index data from any smart contract deployed to Ethereum.