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."

This talk has been presented at GraphQL Galaxy 2022, check out the latest edition of this Tech Conference.

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
Routing in React 18 brings a native app-like user experience and allows applications to transition between different environments. React Router and Next.js have different approaches to routing, with React Router using component-based routing and Next.js using file system-based routing. React server components provide the primitives to address the disadvantages of multipage applications while maintaining the same user experience. Improving navigation and routing in React involves including loading UI, pre-rendering parts of the screen, and using server components for more performant experiences. Next.js and Remix are moving towards a converging solution by combining component-based routing with file system routing.
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
Tom Pressenwurter introduces Redwood.js, a full stack app framework for building GraphQL APIs easily and maintainably. He demonstrates a Redwood.js application with a React-based front end and a Node.js API. Redwood.js offers a simplified folder structure and schema for organizing the application. It provides easy data manipulation and CRUD operations through GraphQL functions. Redwood.js allows for easy implementation of new queries and directives, including authentication and limiting access to data. It is a stable and production-ready framework that integrates well with other front-end technologies.
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
This Talk discusses handling local state in software development, particularly when dealing with asynchronous behavior and API requests. It explores the challenges of managing global state and the need for actions when handling server data. The Talk also highlights the issue of fetching data not in Vuex and the challenges of keeping data up-to-date in Vuex. It mentions alternative tools like Apollo Client and React Query for handling local state. The Talk concludes with a discussion on GitLab going public and the celebration that followed.
Batteries Included Reimagined - The Revival of GraphQL Yoga
GraphQL Galaxy 2021GraphQL Galaxy 2021
33 min
Batteries Included Reimagined - The Revival of GraphQL Yoga
Envelope is a powerful GraphQL plugin system that simplifies server development and allows for powerful plugin integration. It provides conformity for large corporations with multiple GraphQL servers and can be used with various frameworks. Envelope acts as the Babel of GraphQL, allowing the use of non-spec features. The Guild offers GraphQL Hive, a service similar to Apollo Studio, and encourages collaboration with other frameworks and languages.
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
The Talk discusses the challenges and advancements in using GraphQL and React together. It introduces RedwoodJS, a framework that simplifies frontend-backend integration and provides features like code generation, scaffolding, and authentication. The Talk demonstrates how to set up a Redwood project, generate layouts and models, and perform CRUD operations. Redwood automates many GraphQL parts and provides an easy way for developers to get started with GraphQL. It also highlights the benefits of Redwood and suggests checking out RedwoodJS.com for more information.
Adopting GraphQL in an Enterprise
GraphQL Galaxy 2021GraphQL Galaxy 2021
32 min
Adopting GraphQL in an Enterprise
Today's Talk is about adopting GraphQL in an enterprise. It discusses the challenges of using REST APIs and the benefits of GraphQL. The Talk explores different approaches to adopting GraphQL, including coexistence with REST APIs. It emphasizes the power of GraphQL and provides tips for successful adoption. Overall, the Talk highlights the advantages of GraphQL in terms of efficiency, collaboration, and control over APIs.

Workshops on related topic

Master JavaScript Patterns
JSNation 2024JSNation 2024
145 min
Master JavaScript Patterns
Top Content
Featured Workshop
Adrian Hajdin
Adrian Hajdin
During this workshop, participants will review the essential JavaScript patterns that every developer should know. Through hands-on exercises, real-world examples, and interactive discussions, attendees will deepen their understanding of best practices for organizing code, solving common challenges, and designing scalable architectures. By the end of the workshop, participants will gain newfound confidence in their ability to write high-quality JavaScript code that stands the test of time.
Points Covered:
1. Introduction to JavaScript Patterns2. Foundational Patterns3. Object Creation Patterns4. Behavioral Patterns5. Architectural Patterns6. Hands-On Exercises and Case Studies
How It Will Help Developers:
- Gain a deep understanding of JavaScript patterns and their applications in real-world scenarios- Learn best practices for organizing code, solving common challenges, and designing scalable architectures- Enhance problem-solving skills and code readability- Improve collaboration and communication within development teams- Accelerate career growth and opportunities for advancement in the software industry
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
Build Modern Applications Using GraphQL and Javascript
Node Congress 2024Node Congress 2024
152 min
Build Modern Applications Using GraphQL and Javascript
Featured Workshop
Emanuel Scirlet
Miguel Henriques
2 authors
Come and learn how you can supercharge your modern and secure applications using GraphQL and Javascript. In this workshop we will build a GraphQL API and we will demonstrate the benefits of the query language for APIs and what use cases that are fit for it. Basic Javascript knowledge required.
End-To-End Type Safety with React, GraphQL & Prisma
React Advanced 2022React Advanced 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.