GraphQL authorization layer
GraphQL authorization layer, flexible, (not only) directive-based, compatible with all modern GraphQL architectures.
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
Check examples in examples folder:
To integrate graphql-authz into the project you can follow several steps depending on your architecture:
Read more
yarn add @graphql-authz/core
Create rule and rules object
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
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 Apollo Server pluginSee Apollo Server plugin readme or check examples:
Apollo Server (schema-first, directives)
Apollo Server (code-first, extensions)
Configuring Envelop pluginSee Envelop plugin readme or check examples:
Envelop (schema-first, directives)
Configuring express-graphqlEnsure authenticator is configured to add user info to the request object
const authenticator = (req, res, next) => {
const user = someHowAuthenticateUser(req.get("authorization")));
req.user = user;
next();
};
app.use(authenticator); Provide customExecuteFn to graphqlHTTP
import { execute } from 'graphql';
import { graphqlHTTP } from 'express-graphql';
import { wrapExecuteFn } from '@graphql-authz/core';
graphqlHTTP({
...
customExecuteFn: wrapExecuteFn(execute, { rules }),
...
})Apply directive transformer to schema
import { authZDirective } from '@graphql-authz/directive';
const { authZDirectiveTransformer } = authZDirective();
graphqlHTTP({
...
schema: authZDirectiveTransformer(schema),
customExecuteFn: wrapExecuteFn(execute, { rules }),
...
}) Pass additional parameter authSchema to wrapExecuteFn
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 HelixEnsure context parser is configured to perform authentication and add user info to context
import { processRequest } from 'graphql-helix';
processRequest({
...
contextFactory: () => ({
user: someHowAuthenticateUser(req.get("authorization")))
}),
...
}) Provide execute option to processRequest
import { execute } from 'graphql';
import { processRequest } from 'graphql-helix';
import { wrapExecuteFn } from '@graphql-authz/core';
processRequest({
...
execute: wrapExecuteFn(execute, { rules })
...
})Apply directive transformer to schema
import { authZDirective } from '@graphql-authz/directive';
const { authZDirectiveTransformer } = authZDirective();
processRequest({
...
schema: authZDirectiveTransformer(schema),
execute: wrapExecuteFn(execute, { rules }),
...
}) Pass additional parameter authSchema to wrapExecuteFn
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)
Add rules and directive definition to the schema
…Alternatively generate rules and directive definition
import { directiveTypeDefs } from "@graphql-authz/core";
import { authZGraphQLDirective } from "@graphql-authz/directive";
const directive = authZGraphQLDirective(rules);
const authZDirectiveTypeDefs = directiveTypeDefs(directive);
const typeDefs = gql`
${authZDirectiveTypeDefs}
...
`;Pass directive to schema options to generate rules and directive definition
import { authZGraphQLDirective } from "@graphql-authz/directive";
new GraphQLSchema({
...
directives: [authZGraphQLDirective(rules)]
...
});Add authz directive to Query/Mutation/Object/Interface/Field you need to perform authorization on
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])
}Using TypeGraphQL or NestJS decorators
…Alternatively custom decorator-wrapper can be used
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;
}
It looks pretty similar to the directive usage with decorators
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;
}…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
const authSchema = {
Post: { __authz: { rules: ['CanReadPost'] } },
User: {
email: { __authz: { rules: ['IsAdmin'] } }
},
Mutation: {
publishPost: { __authz: { rules: ['CanPublishPost'] } }
},
Query: {
users: { __authz: { rules: ['IsAuthenticated'] } }
}
};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
import { preExecRule } from "@graphql-authz/core";
const IsAuthenticated = preExecRule()(context => !!context.user);Alternatively new class extended from PreExecutionRule could be created
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
No open issues yet, or sync has not completed.