百科.dev
全部条目在线工具AI 编程趋势榜开源项目技术资讯提交条目
登录
< 返回工具列表
G

graphql-authz

> 编程语言
开源

GraphQL 授权层

197 stars0 点赞0 次浏览
访问官网GitHub

工具介绍

GraphQL 授权层

GraphQL authorization layer, flexible, (not only) directive-based, compatible with all modern GraphQL architectures.

Overview

Flexible modern way of adding an authorization layer on top of your existing GraphQL microservices or monolith backend systems.

Full overview can be found in this blog post: https://the-guild.dev/blog/graphql-authz

Features

  • Attaching rules to Query/Mutation/Object/Interface/Field
  • Attaching rules using directives, extensions or authSchema
  • Pre and Post execution rules
  • Any sync/async JS code inside rules
  • Compatible with all modern GraphQL architectures

Examples

Check examples in examples folder:

  • Apollo Server (schema-first, directives)
  • Apollo Server (code-first, extensions)
  • express-graphql (schema-first, directives)
  • GraphQL Helix (schema-first, authSchema)
  • Envelop (schema-first, directives)
  • TypeGraphQL (code-first, extensions)
  • NestJS (code-first, directives)
  • Schema Stitching (gateway, directives)
  • Apollo Federation (gateway, authSchema)

Integration

To integrate graphql-authz into the project you can follow several steps depending on your architecture:

  • Installation
  • Creating Rules
  • Configuring server
    • Configuring Apollo Server plugin
    • Configuring Envelop plugin
    • Configuring express-graphql
    • Configuring graphql-helix
  • Configuring schema for directive usage
    • Schema First
    • Code First
  • Attaching rules
    • Using Directives
      • Schema-First
      • Code-First
    • Using extensions (Code-First only)
      • Using TypeGraphQL or NestJS decorators
      • Using GraphQL.js constructors
      • Using GiraphQL
    • Using AuthSchema

Read more

  • Pre execution rules vs Post execution rules
  • Wildcard rules
  • Composing rules
  • Custom errors

Installation

yarn add @graphql-authz/core

Creating Rules

Create rule and rules object

typescript
import { preExecRule } from "@graphql-authz/core";

const IsAuthenticated = preExecRule()(context => !!context.user);

const rules = {
  IsAuthenticated
} as const;

Alternatively you can create a rule as a class

typescript
import { PreExecutionRule } from "@graphql-authz/core";

class IsAuthenticated extends PreExecutionRule {
  public execute(context) {
    if (!context.user) {
      throw this.error;
    }
  }
}

const rules = {
  IsAuthenticated
} as const;

Configuring server

Configuring Apollo Server plugin

See Apollo Server plugin readme or check examples:

Apollo Server (schema-first, directives)

Apollo Server (code-first, extensions)

Configuring Envelop plugin

See Envelop plugin readme or check examples:

Envelop (schema-first, directives)

Configuring express-graphql

Ensure authenticator is configured to add user info to the request object

typescript
const authenticator = (req, res, next) => {
  const user = someHowAuthenticateUser(req.get("authorization")));
  req.user = user;
  next();
};

app.use(authenticator);

Provide customExecuteFn to graphqlHTTP

typescript
import { execute } from 'graphql';
import { graphqlHTTP } from 'express-graphql';
import { wrapExecuteFn } from '@graphql-authz/core';

graphqlHTTP({
  ...
  customExecuteFn: wrapExecuteFn(execute, { rules }),
  ...
})

For Directives usage

Apply directive transformer to schema

typescript
import { authZDirective } from '@graphql-authz/directive';

const { authZDirectiveTransformer } = authZDirective();

graphqlHTTP({
    ...
    schema: authZDirectiveTransformer(schema),
    customExecuteFn: wrapExecuteFn(execute, { rules }),
    ...
  })

For AuthSchema usage

Pass additional parameter authSchema to wrapExecuteFn

typescript
import { execute } from 'graphql';
import { wrapExecuteFn } from '@graphql-authz/core';

graphqlHTTP({
  ...
  customExecuteFn: wrapExecuteFn(execute, { rules: authZRules, authSchema }),
  ...
})

Check an example: express-graphql (schema-first, directives)

Configuring GraphQL Helix

Ensure context parser is configured to perform authentication and add user info to context

typescript
import { processRequest } from 'graphql-helix';

processRequest({
  ...
  contextFactory: () => ({
    user: someHowAuthenticateUser(req.get("authorization")))
  }),
  ...
})

Provide execute option to processRequest

typescript
import { execute } from 'graphql';
import { processRequest } from 'graphql-helix';
import { wrapExecuteFn } from '@graphql-authz/core';

processRequest({
  ...
  execute: wrapExecuteFn(execute, { rules })
  ...
})

For Directives usage

Apply directive transformer to schema

typescript
import { authZDirective } from '@graphql-authz/directive';

const { authZDirectiveTransformer } = authZDirective();

processRequest({
    ...
    schema: authZDirectiveTransformer(schema),
    execute: wrapExecuteFn(execute, { rules }),
    ...
  })

For AuthSchema usage

Pass additional parameter authSchema to wrapExecuteFn

typescript
import { execute } from 'graphql';
import { processRequest } from 'graphql-helix';
import { wrapExecuteFn } from '@graphql-authz/core';

processRequest({
  ...
  execute: wrapExecuteFn(execute, { rules, authSchema })
  ...
})

Check an example: GraphQL Helix (schema-first, authSchema)

Configuring schema for directive usage

Schema First

Add rules and directive definition to the schema

…

Alternatively generate rules and directive definition

typescript
import { directiveTypeDefs } from "@graphql-authz/core";
import { authZGraphQLDirective } from "@graphql-authz/directive";

const directive = authZGraphQLDirective(rules);
const authZDirectiveTypeDefs = directiveTypeDefs(directive);

const typeDefs = gql`
  ${authZDirectiveTypeDefs}

  ...

`;

Code First

Pass directive to schema options to generate rules and directive definition

typescript
import { authZGraphQLDirective } from "@graphql-authz/directive";

new GraphQLSchema({
  ...
  directives: [authZGraphQLDirective(rules)]
  ...
});

Attaching rules

Using Directives

Add authz directive to Query/Mutation/Object/Interface/Field you need to perform authorization on

Schema-First

typescript
interface TestInterface @authz(rules: [Rule01]) {
  testField1: String! @authz(rules: [Rule02])
}

type TestType implements TestInterface @authz(rules: [Rule01]) {
  testField1: String!
  testField2: Float! @authz(rules: [Rule02])
}

type Query {
  testQuery: TestType! @authz(rules: [Rule01, Rule02])
}

type Mutation {
  testMutation: TestType! @authz(rules: [Rule01, Rule02])
}

Code-First

Using TypeGraphQL or NestJS decorators

…

Alternatively custom decorator-wrapper can be used

typescript
import { IAuthConfig } from "@graphql-authz/core";

function AuthZ(config: IAuthConfig) {
  const args = Object.keys(config)
    .map(
      key => `${key}: ${JSON.stringify(config[key]).replace(/"/g, '')}`
    )
    .join(', ');
  const directiveArgs = `(${args})`;
  return Directive(`@authz${directiveArgs}`);
}

@InterfaceType()
@AuthZ({ rules: ['Rule01'] })
class TestInterface {
  @Field()
  @AuthZ({ rules: ['Rule02'] })
  public testField1!: string;
}

Using extensions (Code-First only)

Using TypeGraphQL or NestJS decorators

It looks pretty similar to the directive usage with decorators

typescript
import { IAuthConfig } from "@graphql-authz/core";

function AuthZ(args: IAuthConfig) {
  return Extensions({
    authz: {
      directives: [
        {
          name: 'authz',
          arguments: args
        }
      ]
    }
  });
}

@InterfaceType()
@AuthZ({ rules: ['Rule01'] })
class TestInterface {
  @Field()
  @AuthZ({ rules: ['Rule02'] })
  public testField1!: string;
}

Using GraphQL.js constructors

…

Using GiraphQL

typescript
import SchemaBuilder from '@giraphql/core';
import AuthzPlugin from '@giraphql/plugin-authz';

const builder = new SchemaBuilder({
  plugins: [AuthzPlugin],
});

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

const Post = builder.objectRef('Post');

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

GiraphQL provides a native GraphQL Authz plugin @giraphql/plugin-authz that helps to attach auth rules to Queries/Mutations/Objects/Interfaces/Fields in a type-safe way

Using AuthSchema

typescript
const authSchema = {
  Post: { __authz: { rules: ['CanReadPost'] } },
  User: {
    email: { __authz: { rules: ['IsAdmin'] } }
  },
  Mutation: {
    publishPost: { __authz: { rules: ['CanPublishPost'] } }
  },
  Query: {
    users: { __authz: { rules: ['IsAuthenticated'] } }
  }
};

Pre execution rules vs Post execution rules

Pre execution rules are executed before any resolvers are called and have context and fieldArgs as arguments.

context is GraphQL context

fieldArgs is an object that has all arguments passed to Query/Mutation/Field the rule is applied to. If the rule is applied to ObjectType or InterfaceType then fieldArgs is an empty object.

If no other data is needed to perform authorization (e.g. actual data from the database or actual response to the request) then the Pre execution rule should be used.

To create simple Pre execution rule preExecRule function should be used

typescript
import { preExecRule } from "@graphql-authz/core";

const IsAuthenticated = preExecRule()(context => !!context.user);

Alternatively new class extended from PreExecutionRule could be created

typescript
import { PreExecutionRule } from "@graphql-authz/core";

class IsAuthenticated extends PreExecutionRule {
  public execute(context) {
    if (!context.user) {
      throw this.error;
    }
  }
}

Post execution rules are executed after all resolvers logic is executed and the result response is ready. Because of that fact, Post execution rules have access to the actual result of query execution. This can resolve authorization cases when the decision depends on attributes of the requested entity, for example, if only the author of the post can see the post if it is in draft status.

In order to create Post execution rule `pos

Issues· 0 开放

查看全部 Issues在 GitHub 打开

暂无开放 Issues,或尚未同步最近议题。

> 标签

TypeScript

暂无评论,来聊聊你的看法吧

> 工具信息

发布日期2026年8月1日
最后更新2026年9月18日
分类编程语言
定价开源

> 相关工具

T
TypeScript
JavaScript 的超集,为前端与全栈提供静态类型
P
Python
通用编程语言,广泛用于 Web、数据与 AI
G
Go
Google 推出的简洁高效系统语言