How to use Graphql Shield with Apollo Server to authorize JWT
Graphql Shield is a nice library to centralize your authorization rules. But how to use it with Apollo Server? Let’s see. For example, what about I want to do authorization according to the information in JWT?
1. Install graphql middleware
npm i graphql-middleware
2. Get the auth info from JWT
1 | const createContext = ({ req }) => { |
3. create a simple rule for one of your GraphQL path
For instance, I want to auth the posts
path;
1 | const isAuthenticated = rule({ cache: "contextual" })( |
4. Apply to Apollo server
Use graphql-middleware
to combine your schema with the permissions
you just created.
1 | import { ApolloServer } from "apollo-server"; |
5. End
It just works! Thanks.
Thanks for reading!
Follow me (albertgao) on twitter, if you want to hear more about my interesting ideas.