Pothos GraphQL
Searching...

AuthZ plugin

This is a simple plugin for integrating with GraphQL AuthZ

For more details on GraphQL AuthZ see the official documentation here

Usage

Install

yarn add @pothos/plugin-authz

Setup

import AuthzPlugin from '@pothos/plugin-authz';

const builder = new SchemaBuilder<{
  AuthZRule: keyof typeof rules;
}>({
  plugins: [AuthzPlugin],
});

This plugin will add the rules to your schema, but you will still need to set up your server (or execute function) to run the authorization checks. The implementation of this depends on how your app is set up.

A simple example that just wraps the execute function might look like:

import { execute } from 'graphql';
import { wrapExecuteFn } from '@graphql-authz/core';
import rules from './auth-rules';

const wrappedExecute = wrapExecuteFn(execute, { rules });

Defining rules for fields

builder.queryType({
  fields: (t) => ({
    users: t.field({
      type: [User],
      authz: {
        rules: ['IsAuthenticated'],
      },
      resolve: () => users,
    }),
  }),
});

Defining rules for types

const Post = builder.objectRef<IPost>('Post');

Post.implement({
  authz: {
    rules: ['CanReadPost'],
  },
  fields: (t) => ({
    id: t.exposeID('id'),
  }),
});

Defining inline composite rules

const Post = builder.objectRef<IPost>('Post');

Post.implement({
  authz: {
    compositeRules: [{ or: ['CanReadPost', 'IsAdmin'] }],
  },
  fields: (t) => ({
    id: t.exposeID('id'),
  }),
});

More details about composite rules are in the documentation of AuthZ