GraphQL Authentication Directives

0.3.2 · active · verified Wed Apr 22

graphql-directive-auth is a utility library designed to simplify common authentication and authorization tasks in GraphQL APIs by providing schema directives. It offers `@isAuthenticated` and `@hasRole` directives, which can be used to protect fields and types based on JWT tokens and user roles. The current stable version is 0.3.2, indicating it's still in a pre-1.0 development phase, which typically implies an irregular release cadence and potential for API changes. Its key differentiators include a straightforward setup with environment variables for default behavior and highly customizable authentication and role-checking functions for more complex scenarios. It ships with TypeScript types, enhancing developer experience in TypeScript projects. It integrates with `graphql-tools` and expects a `graphql` peer dependency, providing a declarative approach to security within the GraphQL schema itself.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates setting up `graphql-directive-auth` with default authentication, protecting types and fields using `@isAuthenticated` and `@hasRole` directives, and accessing authenticated user data within resolvers. It includes type definitions, resolvers, and directive registration.

import { makeExecutableSchema } from 'graphql-tools';
import { AuthDirective } from 'graphql-directive-auth';

// Set APP_SECRET for default JWT verification.
// In a real application, use proper environment management (e.g., dotenv, Kubernetes secrets).
process.env.APP_SECRET = process.env.APP_SECRET ?? 'your_super_secret_key_for_dev';

const typeDefs = `
  directive @isAuthenticated on FIELD_DEFINITION | OBJECT
  directive @hasRole(role: String!) on FIELD_DEFINITION | OBJECT

  type User @isAuthenticated {
    id: ID!
    name: String!
    role: String! @hasRole(role: "admin")
  }

  type Query {
    me: User @isAuthenticated
    adminPanel: String @hasRole(role: "admin")
    publicGreeting: String
  }
`;

const resolvers = {
  Query: {
    me: (root, args, ctx) => {
      // ctx.auth will contain the decoded JWT payload or custom auth object
      if (!ctx.auth || !ctx.auth.user) throw new Error('Not authenticated');
      return { id: ctx.auth.user.id, name: ctx.auth.user.name, role: ctx.auth.user.role };
    },
    adminPanel: () => 'Welcome to the admin panel!',
    publicGreeting: () => 'Hello, world!'
  }
};

const schema = makeExecutableSchema({
  typeDefs,
  resolvers,
  schemaDirectives: {
    ...AuthDirective(), // Registers @isAuthenticated and @hasRole directives
    // Optionally, you can rename them:
    // auth: AuthDirective().isAuthenticated,
    // role: AuthDirective().hasRole
  }
});

// To use this schema, you would typically pass it to a GraphQL server (e.g., Apollo Server).
// For brevity, the server setup is omitted here.
// console.log(schema); // You can inspect the generated schema

view raw JSON →