Search⌘ K
AI Features

Authorization

Explore how to apply authorization in GraphQL by delegating authentication and role-based access control to the business logic layer. Understand the benefits of handling authorization in the Apollo Server context to maintain clear, secure, and testable API implementations.

We'll cover the following...

Authorization

Authorization is a business logic that expresses whether a given user/session/context can invoke an operation, such as reading or writing a piece of data. The following is an example of authorization: “Only admin can edit pizzas.”

Enforcing this kind of behavior should happen in the business logic layer. It’s tempting to place authorization logic in the GraphQL layer like this:

Javascript (babel-node)
updatePizza: (parent, args, context) => {
// check if user is authenticated
if (!context.user) {
throw new AuthenticationError('user not authenticated');
}
// get current pizza record using pizza id
const { id, pizza, toppings } = args;
const index = pizzas.findIndex((pizza) => pizza.id === id)
// create topping as another table, so you also need to get topping using current topping id!
const toppingRecords = toppings.map(({id})=> pizzaToppings.find(({id: pizzaToppingId})=> pizzaToppingId === id))
pizzas[index] = { id, toppings: toppingRecords, pizza}
return pizzas[index];
},

Notice that we define whether the user iss ...