This repository demonstrates how to setup a JS coprocessor that applies some custom auth checks.
The code in this repository is experimental and has been provided for reference purposes only. Community feedback is welcome but this project may not be supported in the same way that repositories in the official Apollo GraphQL GitHub organization are. If you need help you can file an issue on this repository, contact Apollo to talk to an expert, or create a ticket directly in Apollo Studio.
This is an example of how you can use custom directives to do very unique and complicated logic with a coprocessor. It is not required or reccommend for custom auth solutions. Apollo Router supports custom auth providers still using the @requiresScopes
and @policy
directives, and we reccomend you use those.
See this other example instead as a reccomended way to solve this: https://github.com/apollosolutions/example-coprocessor-auth-policy
This example uses @composeDirective
to add our custom directives to the supergraph. The entire SDL is then sent to a coprocessor where it is parsed, mocked, and cached with graphql-js as a full GraphQL schema. On every request we then "execute" the operation against our mock schema that has the custom directive implementation code and runs our auth logic and we return an auth error or continue based on the response.
Note: To run this example, you will need a GraphOS Enterprise plan and must create
/router/.env
based on/router/.env.example
which exportsAPOLLO_KEY
andAPOLLO_GRAPH_REF
.
- Run the subgraph from the
/subgraph
directory withnpm run dev
- Run the coprocessor based on your language of choice by following the README from the appropriate
/*-coprocessor
directory (javascript, Java, golang). - In the
/router
directory, download the router by running./download_router.sh
- In the
/router
directory, compose the schema by running./create_local_schema.sh
- In the
/router
directory, run the router by running./start_router.sh
Now if you run this code in the browser (http://127.0.0.1:4000/), you will be able to query the router and you will see the payload
logged in the terminal by the coprocessor.
In router/router-config.yaml
, the coprocessor is configured with the Router to be called on the SupergraphRequest
stage so that Router handles basic GraphQL validation.
Implemented with JS to parse the schema and operations on every request and execute it against a mock schema.
The auth.js
file implements the authNZ directive logic as if it was on a real GraphQL server. See comments for more details.
Send requests with the x-user-role: ADMIN
header to test operations that require auth.