Authorization

Learn how to validate authentication in GraphQL servers.

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:

Press + to interact
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 ...