Adding Authorization to a GraphQL API

Authorization is the mechanism that controls who can do what on which resource in an application. Although it is a critical part of an application, there are limited resources available on how to build authorization into an app effectively. In this post, I’ll be illustrating how to set up authorization in a GraphQL API using a custom directive and Oso, an open-source authorization library. This tutorial covers the NodeJS variant of Oso, but it also supports Python and other languages.

Requirements

There are a number of users and each of them belongs to one or more user groups. The groups are guest, member and admin. Also a user can be given escalated permission on one or more projects if he/she belongs to a certain project user group (e.g. contributor).

Depending on the membership, users have varying levels of permission on user, project and indicator resources. Specifically

User

  • All users can be fetched if a user belongs to the admin user group.

Project

  • A project or all permitted projects can be queried if a user belongs to the admin or member user group or to the contributor user project group.

    • For a project record, the contract_sum field can be queried only if a user belongs to the admin user group or contributor user project group.

  • The project status can be updated if a user belongs to the admin user group or contributor user project group.

Indicator

  • All permitted project indicators can be fetched if a user belongs to the admin user group or contributor user project group.

 

Building Blocks

Permission Specification on Directive

A directive decorates part of a GraphQL schema or operation with additional configuration. Tools like Apollo Server (and Apollo Client) can read a GraphQL document’s directives and perform custom logic as appropriate.

A directive can be useful to define permission. Below shows the type definitions used to meet the authorization requirements listed above. For example, the auth directive (@auth) is applied to the project query where admin and member are required for the user groups and contributor for the project user group.

 

// src/schema.js
const typeDefs = gql`

  directive @auth(

    userGroups: [UserGroup]

    projGroups: [ProjectGroup]

  ) on OBJECT | FIELD_DEFINITION

 

  …

 

  type User {

    id: ID!

    name: String

    groups: [String]

  }

 

  type Project {

    id: ID!

    name: String

    status: String

    contract_sum: Int @auth(userGroups: [admin], projGroups: [contributor])

  }

 

  type Indicator {

    id: ID!

    project_id: Int

    risk: Int

    quality: Int

  }

 

  type Query {

    users: [User] @auth(userGroups: [admin])

    project(projectId: ID!): Project

      @auth(userGroups: [admin, member], projGroups: [contributor])

    projects: [Project]

      @auth(userGroups: [admin, member], projGroups: [contributor])

    indicators: [Indicator]

      @auth(userGroups: [admin], projGroups: [contributor])

  }

 

  type Mutation {

    updateProjectStatus(projectId: ID!, status: String!): Project

      @auth(userGroups: [admin], projGroups: [contributor])

  }

`;

Policy Building Using Oso

Oso is a batteries-included library for building authorization in your application. Oso gives you a mental model and an authorization system – a set of APIs built on top of a declarative policy language called Polar, plus a debugger and REPL – to define who can do what in your application. You can express common concepts from “users can see their own data” and role-based access control, to others like multi-tenancy, organizations and teams, hierarchies and relationships.

An authorization policy is a set of logical rules for who is allowed to access what resources in an application. For example, the policy that describes the get:project action allows the actor (user) to perform it on the project resource if he/she belongs to required user or project groups. The actor and resource can be either a custom class or one of the built-in classes (Dictionary, List, String …). Note methods of a custom class can be used instead of built-in operations as well.

 

# src/polars/policy.polar
allow(user: User, “list:users”, _: String) if

  user.isRequiredUserGroup();

 

allow(user: User, “get:project”, project: Dictionary) if

  user.isRequiredUserGroup()

  or

  user.isRequiredProjectGroup(project);

 

allow(user: User, “update:project”, projectId: Integer) if

  user.isRequiredUserGroup()

  or

  projectId in user.filterAllowedProjectIds();

 

allow(user: User, “list:indicators”, _: String) if

  user.isRequiredUserGroup()

  or

  user.filterAllowedProjectIds().length > 0;

Policy Enforcement

Within Directive

The auth directive collects the user and project group configuration on an object or field definition. Then it updates the user object in the context and passes it to the resolver. In this way, policy enforcement for queries and mutations can be performed within the resolver and it is more manageable while the number of queries and mutations increases. 


On the other hand, the policy of an object field (e.g. contract_sum) is enforced within the directive. It is because, once a query (e.g. project) or mutation is resolved and its parent object is returned, the directive is executed for the field with different configuration values.

 

// src/utils/directive.js

class AuthDirective extends SchemaDirectiveVisitor {

  …

 

  ensureFieldsWrapped(objectType) {

    if (objectType._authFieldsWrapped) return;

    objectType._authFieldsWrapped = true;

 

    const fields = objectType.getFields();

 

    Object.keys(fields).forEach((fieldName) => {

      const field = fields[fieldName];

      const { resolve = defaultFieldResolver } = field;

      field.resolve = async function (…args) {

        const userGroups = field._userGroups || objectType._userGroups;

        const projGroups = field._projGroups || objectType._projGroups;

        if (!userGroups && !projGroups) {

          return resolve.apply(this, args);

        }

 

        const context = args[2];

        context.user.requires = { userGroups, projGroups };

 

        // check permission of fields that have a specific parent type

        if (args[3].parentType.name == “Project”) {

          const user = User.clone(context.user);

          if (!(await context.oso.isAllowed(user, “get:project”, args[0]))) {

            throw new ForbiddenError(

             JSON.stringify({ requires: user.requires, groups: user.groups })

            );

          }

        }

 

        return resolve.apply(this, args);

      };

    });

  }

}

Within Resolver

The Oso object is instantiated and stored in the context. Then a policy can be enforced with the corresponding actor, action and resource triples. For list endpoints, different strategies can be employed. For example, the projects query fetches all records but returns only authorized records. On the other hand, the indicators query is set to fetch only permitted records, which is more effective when dealing with sensitive data or a large amount of data.

 

// src/resolvers.js
const resolvers = {

  Query: {

    users: async (_, __, context) => {

      const user = User.clone(context.user);

      if (await context.oso.isAllowed(user, “list:users”, “_”)) {

        return await User.fetchUsers();

      } else {

        throw new ForbiddenError(

          JSON.stringify({ requires: user.requires, groups: user.groups })

        );

      }

    },

    project: async (_, args, context) => {

      const user = User.clone(context.user);

      const result = await Project.fetchProjects([args.projectId]);

      if (await context.oso.isAllowed(user, “get:project”, result[0])) {

        return result[0];

      } else {

        throw new ForbiddenError();

      }

    },

    projects: async (_, __, context) => {

      const user = User.clone(context.user);

      const results = await Project.fetchProjects();

      const authorizedResults = [];

      for (const result of results) {

        if (await context.oso.isAllowed(user, “get:project”, result)) {

          authorizedResults.push(result);

        }

      }

      return authorizedResults;

    },

    indicators: async (_, __, context) => {

      const user = User.clone(context.user);

      if (await context.oso.isAllowed(user, “list:indicators”, “_”)) {

        let projectIds;

        if (user.isRequiredUserGroup()) {

          projectIds = [];

        } else {

          projectIds = user.filterAllowedProjectIds();

          if (projectIds.length == 0) {

            throw new Error(“fails to populate project ids”);

          }

        }

        return await Project.fetchProjectIndicators(projectIds);

      } else {

        throw new ForbiddenError();

      }

    },

  },

  Mutation: {

    updateProjectStatus: async (_, args, context) => {

      const user = User.clone(context.user);

      if (

        await context.oso.isAllowed(

          User, “update:project”, parseInt(args.projectId)

        )

      ) {

        return Project.updateProjectStatus(args.projectId, args.status);

      } else {

        throw new ForbiddenError();

      }

    },

  },

};

Examples

The application source can be found in this GitHub repository and it can be started as follows.

 

docker-compose up
# if first time
docker-compose up –build

Apollo Studio can be used to query the example API. Note the server is running on port 5000 and it is expected to have one of the following values in the name request header.

 

  • guest-user

    • user group: guest

  • member-user

    • user group: member

    • user project group: contributor of project 1 and 3

  • admin-user

    • user group: admin

  • contributor-user

    • user group: guest

    • user project group: contributor of project 1, 3, 5, 8 and 12

 

The member user can query the project thanks to her user group membership. Also, as the user is a contributor of project 1 and 3, she has access to contract_sum.

The query returns an error if a project that she is not a contributor is requested. The project query is resolved because of her user group membership while contract_sum turns to null.

The contributor user can query all permitted projects without an error as shown below.

Conclusion

In this post, it is illustrated how to build authorization in a GraphQL API using a custom directive and an open source authorization library, Oso. A custom directive is effective to define permission on a schema, to pass configuration to the resolver and even to enforce policies directly. The Oso library helps build policies in a declarative way while expressing common concepts. Although it’s not covered in this post, the library supports building common authorization models such as role-based access control, multi-tenancy, hierarchies and relationships. It has a huge potential! I hope you find this post useful when building authorization in an application.

Enjoyed this blog?

Share it with your network!

Move faster with confidence