Slide 1

Slide 1 text

Becoming a “Secret” Agent Securing Your GraphQL Backend with JWTs

Slide 2

Slide 2 text

@samjulien

Slide 3

Slide 3 text

Auth in GraphQL can be confusing. @samjulien

Slide 4

Slide 4 text

app.get("/api/super-secret", checkAuth, function(req, res) { res.json({ message: "Shhh! Very secret!" }); }); @samjulien

Slide 5

Slide 5 text

app.get("/api/super-secret", checkAuth, function(req, res) { res.json({ message: "Shhh! Very secret!" }); }); @samjulien

Slide 6

Slide 6 text

app.use( "/graphql", graphqlHTTP({ schema: MyGraphQLSchema, graphiql: true }) ); @samjulien

Slide 7

Slide 7 text

app.use( "/graphql", graphqlHTTP({ schema: MyGraphQLSchema, graphiql: true }) ); 🤔 @samjulien

Slide 8

Slide 8 text

Sam Julien @samjulien | samjulien.com DevRel Manager at Auth0 Getting Started in Developer Relations & Guide to Tiny Experiments Developer Microskills Newsletter

Slide 9

Slide 9 text

@samjulien

Slide 10

Slide 10 text

Some Auth Background The What & Why of JWTs Authorization in GraphQL @samjulien

Slide 11

Slide 11 text

Some Auth Background

Slide 12

Slide 12 text

Authentication & Authorization @samjulien

Slide 13

Slide 13 text

Authentication @samjulien

Slide 14

Slide 14 text

Authentication Are you who you say you are? @samjulien

Slide 15

Slide 15 text

Authorization @samjulien

Slide 16

Slide 16 text

Authorization Do you have permission to access resources? @samjulien

Slide 17

Slide 17 text

@samjulien

Slide 18

Slide 18 text

@samjulien

Slide 19

Slide 19 text

@samjulien

Slide 20

Slide 20 text

The GraphQL server doesn’t necessarily care about users proving who they are — it cares who has access to what. @samjulien

Slide 21

Slide 21 text

Access @samjulien

Slide 22

Slide 22 text

Backend + Frontend on the Same Server @samjulien

Slide 23

Slide 23 text

GraphQL + NextJS on the Same Server @samjulien

Slide 24

Slide 24 text

GraphQL + NextJS on the Same Server @samjulien

Slide 25

Slide 25 text

@samjulien

Slide 26

Slide 26 text

@samjulien

Slide 27

Slide 27 text

Access @samjulien

Slide 28

Slide 28 text

Delegated Access @samjulien

Slide 29

Slide 29 text

GraphQL + NextJS on the Same Server @samjulien

Slide 30

Slide 30 text

@samjulien

Slide 31

Slide 31 text

@samjulien

Slide 32

Slide 32 text

We need something other than a cookie for this… @samjulien

Slide 33

Slide 33 text

💡Can contain useful information ✅ Can be signed and verified @samjulien

Slide 34

Slide 34 text

…but what is that thing and how do we (safely) create it? @samjulien

Slide 35

Slide 35 text

Token @samjulien

Slide 36

Slide 36 text

Authorization Server @samjulien

Slide 37

Slide 37 text

Helps make access control decisions in your app or API. Authorization Server @samjulien

Slide 38

Slide 38 text

Access Token @samjulien

Slide 39

Slide 39 text

Access Token Informs the API the bearer has been authorized. @samjulien

Slide 40

Slide 40 text

@samjulien

Slide 41

Slide 41 text

@samjulien

Slide 42

Slide 42 text

@samjulien

Slide 43

Slide 43 text

Access Token @samjulien

Slide 44

Slide 44 text

Authorization: Bearer @samjulien

Slide 45

Slide 45 text

💡Can contain useful information ✅ Can be signed and verified @samjulien

Slide 46

Slide 46 text

JSON Web Tokens (JWTs)

Slide 47

Slide 47 text

eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxM jM0NTY3ODkwIiwibmFtZSI6IkhlbGxvIEdyYXBoUUwiLCJlbWF pbCI6ImhlbGxvQGdyYXBocWwuY29tIiwiaWF0IjoxNTE2MjM5M DIyfQ.cJutaCScQJXsGTL6ynH7BRMnQj_P2yl0a58jUhnLDq8 @samjulien

Slide 48

Slide 48 text

{ "sub": "1234567890", "name": "Hello GraphQL", "email": "hello@graphql.com", "iat": 1516239022 } 🤖 eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9 @samjulien

Slide 49

Slide 49 text

eyJhbGciOiJIUzI1NiIsInR5c CI6IkpXVCJ9.eyJzdWIiOiIxM jM0NTY3ODkwIiwibmFtZSI6Ik hlbGxvIEdyYXBoUUwiLCJlbWF pbCI6ImhlbGxvQGdyYXBocWwu Y29tIiwiaWF0IjoxNTE2MjM5M DIyfQ.cJutaCScQJXsGTL6ynH 7BRMnQj_P2yl0a58jUhnLDq8 Header (Algorithm and Token Type) { "alg": "HS256", "typ": "JWT" } @samjulien

Slide 50

Slide 50 text

eyJhbGciOiJIUzI1NiIsInR5c CI6IkpXVCJ9.eyJzdWIiOiIxM jM0NTY3ODkwIiwibmFtZSI6Ik hlbGxvIEdyYXBoUUwiLCJlbWF pbCI6ImhlbGxvQGdyYXBocWwu Y29tIiwiaWF0IjoxNTE2MjM5M DIyfQ.cJutaCScQJXsGTL6ynH 7BRMnQj_P2yl0a58jUhnLDq8 Payload (Data and Claims) { "sub": "1234567890", "name": "Hello GraphQL", "email": "hello@graphql.com", "iat": 1516239022 } @samjulien

Slide 51

Slide 51 text

eyJhbGciOiJIUzI1NiIsInR5c CI6IkpXVCJ9.eyJzdWIiOiIxM jM0NTY3ODkwIiwibmFtZSI6Ik hlbGxvIEdyYXBoUUwiLCJlbWF pbCI6ImhlbGxvQGdyYXBocWwu Y29tIiwiaWF0IjoxNTE2MjM5M DIyfQ.cJutaCScQJXsGTL6ynH 7BRMnQj_P2yl0a58jUhnLDq8 Verify Signature x Signature ✍ @samjulien

Slide 52

Slide 52 text

💡Can contain useful information ✅ Can be signed and verified @samjulien

Slide 53

Slide 53 text

{ "sub": "1234567890", "name": “Hello GraphQL”, "iat": 1516239022, "https://hasura.io/jwt/claims": { "x-hasura-allowed-roles": ["editor","user", "mod"], "x-hasura-default-role": "user", "x-hasura-user-id": "1234567890", "x-hasura-org-id": "123", "x-hasura-custom": "custom-value" } } @samjulien

Slide 54

Slide 54 text

{ "sub": "1234567890", "name": “Hello GraphQL”, "iat": 1516239022, "https://hasura.io/jwt/claims": { "x-hasura-allowed-roles": ["editor","user", "mod"], "x-hasura-default-role": "user", "x-hasura-user-id": "1234567890", "x-hasura-org-id": "123", "x-hasura-custom": "custom-value" } } @samjulien

Slide 55

Slide 55 text

@samjulien

Slide 56

Slide 56 text

@samjulien

Slide 57

Slide 57 text

Your user management will (likely) live outside of your GraphQL server. @samjulien

Slide 58

Slide 58 text

Should you just build your own Authorization Server? @samjulien

Slide 59

Slide 59 text

How will you be sure you… @samjulien

Slide 60

Slide 60 text

How will you be sure you… Implement proper password controls? Implement secure password recovery mechanisms? Transmit passwords securely? Correctly implement authentication and error messages? Prevent brute force attacks? @samjulien

Slide 61

Slide 61 text

How will you be sure you… Implement proper password controls? Implement secure password recovery mechanisms? Transmit passwords securely? Correctly implement authentication and error messages? Prevent brute force attacks? 😫 @samjulien

Slide 62

Slide 62 text

Consider outsourcing this piece of your app. @samjulien

Slide 63

Slide 63 text

@samjulien

Slide 64

Slide 64 text

@samjulien

Slide 65

Slide 65 text

Authorization in GraphQL

Slide 66

Slide 66 text

Authorization: Bearer xxx.yyy.zzz @samjulien

Slide 67

Slide 67 text

Your GraphQL server needs to verify the access token with a public key. @samjulien

Slide 68

Slide 68 text

You can then parse claims for authorization. @samjulien

Slide 69

Slide 69 text

So how do we do that? @samjulien

Slide 70

Slide 70 text

First, grab the token from the request and add it to context. @samjulien

Slide 71

Slide 71 text

const server = new ApolloServer({ typeDefs: schema, resolvers, context: async ({ req }) => { const token = req.headers["Authorization"]; return { token }; } }); @samjulien

Slide 72

Slide 72 text

const server = new ApolloServer({ typeDefs: schema, resolvers, context: async ({ req }) => { const token = req.headers["Authorization"]; return { token }; } }); @samjulien

Slide 73

Slide 73 text

We still need to verify the token. @samjulien

Slide 74

Slide 74 text

verifyToken(token): Payload @samjulien

Slide 75

Slide 75 text

Authorization: Bearer xxx.yyy.zzz @samjulien

Slide 76

Slide 76 text

const bearerToken = token.split(" ")[1]; @samjulien

Slide 77

Slide 77 text

eyJhbGciOiJIUzI1NiIsInR5c CI6IkpXVCJ9.eyJzdWIiOiIxM jM0NTY3ODkwIiwibmFtZSI6Ik hlbGxvIEdyYXBoUUwiLCJlbWF pbCI6ImhlbGxvQGdyYXBocWwu Y29tIiwiaWF0IjoxNTE2MjM5M DIyfQ.cJutaCScQJXsGTL6ynH 7BRMnQj_P2yl0a58jUhnLDq8 Verify Signature x Signature ✍ @samjulien

Slide 78

Slide 78 text

const client = jwksClient({ jwksUri: `https://${process.env.AUTH_DOMAIN}/.well-known/jwks.json` }); @samjulien

Slide 79

Slide 79 text

const client = jwksClient({ jwksUri: `https://${process.env.AUTH_DOMAIN}/.well-known/jwks.json` }); @samjulien

Slide 80

Slide 80 text

function getJwksClientKey(header, callback) { client.getSigningKey(header.kid, function(error, key) { const signingKey = key.publicKey || key.rsaPublicKey; callback(null, signingKey); }); } @samjulien

Slide 81

Slide 81 text

function getJwksClientKey(header, callback) { client.getSigningKey(header.kid, function(error, key) { const signingKey = key.publicKey || key.rsaPublicKey; callback(null, signingKey); }); } @samjulien

Slide 82

Slide 82 text

jwt.verify(bearerToken, getJwksClientKey, { audience: process.env.API_IDENTIFIER, issuer: `https://${process.env.AUTH_DOMAIN}/`, algorithms: ["RS256"] }); @samjulien

Slide 83

Slide 83 text

jwt.verify(bearerToken, getJwksClientKey, { audience: process.env.API_IDENTIFIER, issuer: `https://${process.env.AUTH_DOMAIN}/`, algorithms: ["RS256"] }); @samjulien

Slide 84

Slide 84 text

jwt.verify(bearerToken, getJwksClientKey, { audience: process.env.API_IDENTIFIER, issuer: `https://${process.env.AUTH_DOMAIN}/`, algorithms: ["RS256"] }); @samjulien

Slide 85

Slide 85 text

try { const payload = await jwt.verify(...); return payload; } catch (error) { throw new Error("Invalid token!"); } @samjulien

Slide 86

Slide 86 text

try { const payload = await jwt.verify(...); return payload; } catch (error) { throw new Error("Invalid token!"); } @samjulien

Slide 87

Slide 87 text

verifyToken(token): Payload @samjulien

Slide 88

Slide 88 text

Where do we use this? @samjulien

Slide 89

Slide 89 text

Inside of resolvers? @samjulien

Slide 90

Slide 90 text

Back in Context @samjulien

Slide 91

Slide 91 text

const createContext = async req => { const db = await startDatabase(); let token = null; let currentUser = null; try { token = req.headers["Authorization"]; if (token) { const payload = await verifyToken(token); currentUser = await db.query.users.where({ id: payload.sub }); } } catch (error) { throw new Error("Unable to authenticate."); } return { db, token, currentUser }; }; @samjulien

Slide 92

Slide 92 text

const createContext = async req => { const db = await startDatabase(); let token = null; let currentUser = null; try { token = req.headers["Authorization"]; if (token) { const payload = await verifyToken(token); currentUser = await db.query.users.where({ id: payload.sub }); } } catch (error) { throw new Error("Unable to authenticate."); } return { db, token, currentUser }; }; @samjulien

Slide 93

Slide 93 text

const createContext = async req => { const db = await startDatabase(); let token = null; let currentUser = null; try { token = req.headers["Authorization"]; if (token) { const payload = await verifyToken(token); currentUser = await db.query.users.where({ id: payload.sub }); } } catch (error) { throw new Error("Unable to authenticate."); } return { db, token, currentUser }; }; @samjulien

Slide 94

Slide 94 text

const createContext = async req => { const db = await startDatabase(); let token = null; let currentUser = null; try { token = req.headers["Authorization"]; if (token) { const payload = await verifyToken(token); currentUser = await db.query.users.where({ id: payload.sub }); } } catch (error) { throw new Error("Unable to authenticate."); } return { db, token, currentUser }; }; @samjulien

Slide 95

Slide 95 text

const createContext = async req => { const db = await startDatabase(); let token = null; let currentUser = null; try { token = req.headers["Authorization"]; if (token) { const payload = await verifyToken(token); currentUser = await db.query.users.where({ id: payload.sub }); } } catch (error) { throw new Error("Unable to authenticate."); } return { db, token, currentUser }; }; @samjulien

Slide 96

Slide 96 text

const createContext = async req => { const db = await startDatabase(); let token = null; let currentUser = null; try { token = req.headers["Authorization"]; if (token) { const payload = await verifyToken(token); currentUser = await db.query.users.where({ id: payload.sub }); } } catch (error) { throw new Error("Unable to authenticate."); } return { db, token, currentUser }; }; @samjulien

Slide 97

Slide 97 text

const createContext = async req => { const db = await startDatabase(); let token = null; let currentUser = null; try { token = req.headers["Authorization"]; if (token) { const payload = await verifyToken(token); currentUser = await db.query.users.where({ id: payload.sub }); } } catch (error) { throw new Error("Unable to authenticate."); } return { db, token, currentUser }; }; @samjulien

Slide 98

Slide 98 text

const createContext = async req => { const db = await startDatabase(); let token = null; let currentUser = null; try { token = req.headers["Authorization"]; if (token) { const payload = await verifyToken(token); currentUser = await db.query.users.where({ id: payload.sub }); } } catch (error) { throw new Error("Unable to authenticate."); } return { db, token, currentUser }; }; @samjulien

Slide 99

Slide 99 text

const server = new ApolloServer({ typeDefs: schema, resolvers, context: async ({ req }) => createContext(req) }); @samjulien

Slide 100

Slide 100 text

const server = new ApolloServer({ typeDefs: schema, resolvers, context: async ({ req }) => createContext(req) }); @samjulien

Slide 101

Slide 101 text

createEvent: async (parent, args, context, info) => { if (!context.currentUser) { throw new Error("Must be logged in for this!"); } const { currentUser } = context; if (hasPermissions(currentUser.permissions, PERMISSIONS.CREATE)) { return await createEventInDb({ ...args, ...context }); } }; @samjulien

Slide 102

Slide 102 text

createEvent: async (parent, args, context, info) => { if (!context.currentUser) { throw new Error("Must be logged in for this!"); } const { currentUser } = context; if (hasPermissions(currentUser.permissions, PERMISSIONS.CREATE)) { return await createEventInDb({ ...args, ...context }); } }; @samjulien

Slide 103

Slide 103 text

createEvent: async (parent, args, context, info) => { if (!context.currentUser) { throw new Error("Must be logged in for this!"); } const { currentUser } = context; if (hasPermissions(currentUser.permissions, PERMISSIONS.CREATE)) { return await createEventInDb({ ...args, ...context }); } }; @samjulien

Slide 104

Slide 104 text

Wrapping (Composing) Resolvers @samjulien

Slide 105

Slide 105 text

export const isAuthenticated = next => (parent, args, context, info) => { if (!context.currentUser) { throw new Error("You must be authenticated!"); } return next(parent, args, context, info); }; @samjulien

Slide 106

Slide 106 text

export const isAuthenticated = next => (parent, args, context, info) => { if (!context.currentUser) { throw new Error("You must be authenticated!"); } return next(parent, args, context, info); }; @samjulien

Slide 107

Slide 107 text

export const isAuthenticated = next => (parent, args, context, info) => { if (!context.currentUser) { throw new Error("You must be authenticated!"); } return next(parent, args, context, info); }; @samjulien

Slide 108

Slide 108 text

export const isAuthenticated = next => (parent, args, context, info) => { if (!context.currentUser) { throw new Error("You must be authenticated!"); } return next(parent, args, context, info); }; @samjulien

Slide 109

Slide 109 text

createEvent: isAuthenticated(async (parent, args, context, info) => { const { currentUser } = context; if (hasPermissions(currentUser.permissions, PERMISSIONS.CREATE)) { return await createEventInDb({ ...args, ...context }); } }); @samjulien

Slide 110

Slide 110 text

createEvent: isAuthenticated(async (parent, args, context, info) => { const { currentUser } = context; if (hasPermissions(currentUser.permissions, PERMISSIONS.CREATE)) { return await createEventInDb({ ...args, ...context }); } }); @samjulien

Slide 111

Slide 111 text

createEvent: isAuthenticated(async (parent, args, context, info) => { const { currentUser } = context; if (hasPermissions(currentUser.permissions, PERMISSIONS.CREATE)) { return await createEventInDb({ ...args, ...context }); } }); @samjulien

Slide 112

Slide 112 text

export const checkPermission = permission => next => ( parent, args, context, info ) => { if (!hasPermissions(context.currentUser.permissions, permission)) { throw new Error("You don't have permission!"); } return next(parent, args, context, info); }; @samjulien

Slide 113

Slide 113 text

createEvent: isAuthenticated( checkPermissions(PERMISSIONS.CREATE)( async (parent, args, context, info) => { return await createEventInDb({ ...args, ...context }); } ) ); @samjulien

Slide 114

Slide 114 text

createEvent: isAuthenticated( checkPermissions(PERMISSIONS.CREATE)( async (parent, args, context, info) => { return await createEventInDb({ ...args, ...context }); } ) ); @samjulien

Slide 115

Slide 115 text

createEvent: isAuthenticated( checkPermissions(PERMISSIONS.CREATE)( async (parent, args, context, info) => { return await createEventInDb({ ...args, ...context }); } ) ); @samjulien

Slide 116

Slide 116 text

graphql-resolvers Lucas Constantino @samjulien

Slide 117

Slide 117 text

export const isAuthenticated = (parent, args, context, info) => { return context.currentUser ? skip : new Error("Not authenticated!"); }; @samjulien

Slide 118

Slide 118 text

export const isAuthenticated = (parent, args, context, info) => { return context.currentUser ? skip : new Error("Not authenticated!"); }; @samjulien

Slide 119

Slide 119 text

export const isAuthenticated = (parent, args, context, info) => { return context.currentUser ? skip : new Error("Not authenticated!"); }; @samjulien

Slide 120

Slide 120 text

createEvent: combineResolvers( isAuthenticated, checkPermissions(PERMISSIONS.CREATE), async (parent, args, context, info) => { return await createEventInDb({ ...args, ...context }); } ); @samjulien

Slide 121

Slide 121 text

createEvent: combineResolvers( isAuthenticated, checkPermissions(PERMISSIONS.CREATE), async (parent, args, context, info) => { return await createEventInDb({ ...args, ...context }); } ); @samjulien

Slide 122

Slide 122 text

createEvent: combineResolvers( isAuthenticated, checkPermissions(PERMISSIONS.CREATE), async (parent, args, context, info) => { return await createEventInDb({ ...args, ...context }); } ); @samjulien

Slide 123

Slide 123 text

graphql-auth Kurt Kemple @samjulien

Slide 124

Slide 124 text

import withAuth from 'graphql-auth'; const resolvers = { Query: { users: withAuth(['users:view'], (root, args, context) => { ... }), ... } } @samjulien

Slide 125

Slide 125 text

import withAuth from 'graphql-auth'; const resolvers = { Query: { users: withAuth(['users:view'], (root, args, context) => { ... }), ... } } @samjulien

Slide 126

Slide 126 text

import withAuth from 'graphql-auth'; const resolvers = { Query: { users: withAuth(['users:view'], (root, args, context) => { ... }), ... } } @samjulien

Slide 127

Slide 127 text

graphql-modules Uri Goldshtein (& Many Others) @samjulien

Slide 128

Slide 128 text

import { GraphQLModule } from "@graphql-modules/core"; const MyModule = new GraphQLModule({ /*...*/ resolversComposition: { "Mutation.createEvent": [ isAuthenticated(), checkPermissions(PERMISSIONS.CREATE) ] } }); @samjulien

Slide 129

Slide 129 text

import { GraphQLModule } from "@graphql-modules/core"; const MyModule = new GraphQLModule({ /*...*/ resolversComposition: { "Mutation.createEvent": [ isAuthenticated(), checkPermissions(PERMISSIONS.CREATE) ] } }); @samjulien

Slide 130

Slide 130 text

Middleware @samjulien

Slide 131

Slide 131 text

graphql-middleware Prisma Community (Matic Zavadlal) @samjulien

Slide 132

Slide 132 text

const authMiddleware = { Mutation: { createEvent: isAuthenticated }, } const server = new GraphQLServer({ typeDefs, resolvers, [authMiddleware], }) @samjulien

Slide 133

Slide 133 text

const authMiddleware = { Mutation: { createEvent: isAuthenticated }, } const server = new GraphQLServer({ typeDefs, resolvers, [authMiddleware], }) @samjulien

Slide 134

Slide 134 text

const authMiddleware = { Mutation: { createEvent: isAuthenticated }, } const server = new GraphQLServer({ typeDefs, resolvers, [authMiddleware], }) @samjulien

Slide 135

Slide 135 text

graphql-shield Matic Zavadlal @samjulien

Slide 136

Slide 136 text

No content

Slide 137

Slide 137 text

const isAuthenticated = rule({ cache: "contextual" })( async (parent, args, ctx, info) => { return ctx.user !== null; } ); const isAdmin = rule({ cache: "contextual" })( async (parent, args, ctx, info) => { return ctx.user.role === "admin"; } ); const isEditor = rule({ cache: "contextual" })( async (parent, args, ctx, info) => { return ctx.user.role === "editor"; } ); @samjulien

Slide 138

Slide 138 text

const isAuthenticated = rule({ cache: "contextual" })( async (parent, args, ctx, info) => { return ctx.user !== null; } ); const isAdmin = rule({ cache: "contextual" })( async (parent, args, ctx, info) => { return ctx.user.role === "admin"; } ); const isEditor = rule({ cache: "contextual" })( async (parent, args, ctx, info) => { return ctx.user.role === "editor"; } ); @samjulien

Slide 139

Slide 139 text

const permissions = shield({ Query: { frontPage: not(isAuthenticated), events: and(isAuthenticated, or(isAdmin, isEditor)), }, Mutation: { createEvent: isAuthenticated, }, }); const server = new GraphQLServer({ typeDefs, resolvers, middlewares: [permissions], context: (req) => ({ ...req, user: getUser(req), }), }); @samjulien

Slide 140

Slide 140 text

const permissions = shield({ Query: { frontPage: not(isAuthenticated), events: and(isAuthenticated, or(isAdmin, isEditor)), }, Mutation: { createEvent: isAuthenticated, }, }); const server = new GraphQLServer({ typeDefs, resolvers, middlewares: [permissions], context: (req) => ({ ...req, user: getUser(req), }), }); @samjulien

Slide 141

Slide 141 text

const permissions = shield({ Query: { frontPage: not(isAuthenticated), events: and(isAuthenticated, or(isAdmin, isEditor)), }, Mutation: { createEvent: isAuthenticated, }, }); const server = new GraphQLServer({ typeDefs, resolvers, middlewares: [permissions], context: (req) => ({ ...req, user: getUser(req), }), }); @samjulien

Slide 142

Slide 142 text

Models @samjulien

Slide 143

Slide 143 text

export const Dog = { getAll: () => { /* logic to get all dogs */ }, getById: (id) => { /* logic to get a single dog */ }, getByGroupId: (id) => { /* logic to get a group of dogs */ }, }; @samjulien

Slide 144

Slide 144 text

export const generateDogModel = ({ currentUser }) => ({ getAll: () => { /* logic to get all dogs */ }, getById: (id) => { /* logic to get a single dog */ }, getByGroupId: (id) => { /* logic to get a group of dogs */ }, }); @samjulien

Slide 145

Slide 145 text

getAll: () => { if(!currentUser || !currentUser.roles.includes('admin')) return null; return fetch(`${API_URL}/dog`); } @samjulien

Slide 146

Slide 146 text

getAll: () => { if(!currentUser || !currentUser.roles.includes('admin')) return null; return fetch(`${API_URL}/dog`); } @samjulien

Slide 147

Slide 147 text

const createContext = async req => { /* previous code hidden but unchanged */ return { db, token, currentUser, models: { Dog: generateDogModel({ currentUser }), }, }; }; @samjulien

Slide 148

Slide 148 text

const createContext = async req => { /* previous code hidden but unchanged */ return { db, token, currentUser, models: { Dog: generateDogModel({ currentUser }), }, }; }; @samjulien

Slide 149

Slide 149 text

Custom Directives @samjulien

Slide 150

Slide 150 text

@deprecated(reason: “Field `eventLocation` replaces `location`.") @samjulien

Slide 151

Slide 151 text

type Event { id: ID description: String! eventLocation: String! location: String! @deprecated(reason: "Field `eventLocation` replaces `location`.") } @samjulien

Slide 152

Slide 152 text

Part of the GraphQL Spec Change behavior at runtime Many use cases Directives @samjulien

Slide 153

Slide 153 text

We can use custom directives to control access down to the field level. @samjulien

Slide 154

Slide 154 text

directive @hasPermission(permission: String) on FIELD_DEFINITION Anatomy of a Directive @samjulien

Slide 155

Slide 155 text

directive @hasPermission(permission: String) on FIELD_DEFINITION Name of the Directive @samjulien

Slide 156

Slide 156 text

directive @hasPermission(permission: String) on FIELD_DEFINITION Argument @samjulien

Slide 157

Slide 157 text

directive @hasPermission(permission: String) on FIELD_DEFINITION Where it Works @samjulien

Slide 158

Slide 158 text

directive @hasPermission(permission: String) on FIELD_DEFINITION @samjulien

Slide 159

Slide 159 text

class HasPermissionDirective extends SchemaDirectiveVisitor { visitFieldDefinition(field) { const { permission } = this.args; const { resolve = defaultFieldResolver } = field; field.resolve = ({ ...args }) => { const context = args[2]; if (!context.currentUser) { throw new Error("Must be logged in!"); } if (hasPermission(context.currentUser, permission)) { return resolve.apply(this, args); } else { throw new Error("Not authorized!"); } }; } } @samjulien

Slide 160

Slide 160 text

class HasPermissionDirective extends SchemaDirectiveVisitor { visitFieldDefinition(field) { const { permission } = this.args; const { resolve = defaultFieldResolver } = field; field.resolve = ({ ...args }) => { const context = args[2]; if (!context.currentUser) { throw new Error("Must be logged in!"); } if (hasPermission(context.currentUser, permission)) { return resolve.apply(this, args); } else { throw new Error("Not authorized!"); } }; } } @samjulien

Slide 161

Slide 161 text

class HasPermissionDirective extends SchemaDirectiveVisitor { visitFieldDefinition(field) { const { permission } = this.args; const { resolve = defaultFieldResolver } = field; field.resolve = ({ ...args }) => { const context = args[2]; if (!context.currentUser) { throw new Error("Must be logged in!"); } if (hasPermission(context.currentUser, permission)) { return resolve.apply(this, args); } else { throw new Error("Not authorized!"); } }; } } @samjulien

Slide 162

Slide 162 text

class HasPermissionDirective extends SchemaDirectiveVisitor { visitFieldDefinition(field) { const { permission } = this.args; const { resolve = defaultFieldResolver } = field; field.resolve = ({ ...args }) => { const context = args[2]; if (!context.currentUser) { throw new Error("Must be logged in!"); } if (hasPermission(context.currentUser, permission)) { return resolve.apply(this, args); } else { throw new Error("Not authorized!"); } }; } } @samjulien

Slide 163

Slide 163 text

class HasPermissionDirective extends SchemaDirectiveVisitor { visitFieldDefinition(field) { const { permission } = this.args; const { resolve = defaultFieldResolver } = field; field.resolve = ({ ...args }) => { const context = args[2]; if (!context.currentUser) { throw new Error("Must be logged in!"); } if (hasPermission(context.currentUser, permission)) { return resolve.apply(this, args); } else { throw new Error("Not authorized!"); } }; } } @samjulien

Slide 164

Slide 164 text

class HasPermissionDirective extends SchemaDirectiveVisitor { visitFieldDefinition(field) { const { permission } = this.args; const { resolve = defaultFieldResolver } = field; field.resolve = ({ ...args }) => { const context = args[2]; if (!context.currentUser) { throw new Error("Must be logged in!"); } if (hasPermission(context.currentUser, permission)) { return resolve.apply(this, args); } else { throw new Error("Not authorized!"); } }; } } @samjulien

Slide 165

Slide 165 text

class HasPermissionDirective extends SchemaDirectiveVisitor { visitFieldDefinition(field) { const { permission } = this.args; const { resolve = defaultFieldResolver } = field; field.resolve = ({ ...args }) => { const context = args[2]; if (!context.currentUser) { throw new Error("Must be logged in!"); } if (hasPermission(context.currentUser, permission)) { return resolve.apply(this, args); } else { throw new Error("Not authorized!"); } }; } } @samjulien

Slide 166

Slide 166 text

class HasPermissionDirective extends SchemaDirectiveVisitor { visitFieldDefinition(field) { const { permission } = this.args; const { resolve = defaultFieldResolver } = field; field.resolve = ({ ...args }) => { const context = args[2]; if (!context.currentUser) { throw new Error("Must be logged in!"); } if (hasPermission(context.currentUser, permission)) { return resolve.apply(this, args); } else { throw new Error("Not authorized!"); } }; } } @samjulien

Slide 167

Slide 167 text

const schema = makeExecutableSchema({ typeDefs, schemaDirectives: { hasPermission: HasPermissionDirective } }); @samjulien

Slide 168

Slide 168 text

const schema = makeExecutableSchema({ typeDefs, schemaDirectives: { hasPermission: HasPermissionDirective } }); @samjulien

Slide 169

Slide 169 text

type Mutation: { createEvent: Event @hasPermission(permission: PERMISSIONS.CREATE) } @samjulien

Slide 170

Slide 170 text

type Mutation: { createEvent: Event @hasPermission(permission: PERMISSIONS.CREATE) } @samjulien

Slide 171

Slide 171 text

⚠ Couples logic to schema. 😅 Can be quite difficult. 🧪 Requires exhaustive testing. Downsides @samjulien

Slide 172

Slide 172 text

Let’s Review

Slide 173

Slide 173 text

@samjulien

Slide 174

Slide 174 text

GraphQL + NextJS on the Same Server @samjulien

Slide 175

Slide 175 text

@samjulien

Slide 176

Slide 176 text

@samjulien

Slide 177

Slide 177 text

eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxM jM0NTY3ODkwIiwibmFtZSI6IkhlbGxvIEdyYXBoUUwiLCJlbWF pbCI6ImhlbGxvQGdyYXBocWwuY29tIiwiaWF0IjoxNTE2MjM5M DIyfQ.cJutaCScQJXsGTL6ynH7BRMnQj_P2yl0a58jUhnLDq8 @samjulien

Slide 178

Slide 178 text

💡Can contain useful information ✅ Can be signed and verified @samjulien

Slide 179

Slide 179 text

const createContext = async req => { const db = await startDatabase(); let token = null; let currentUser = null; try { token = req.headers["Authorization"]; if (token) { const payload = await verifyToken(token); currentUser = await db.query.users.where({ id: payload.sub }); } } catch (error) { throw new Error("Unable to authenticate."); } return { db, token, currentUser }; }; @samjulien

Slide 180

Slide 180 text

createEvent: async (parent, args, context, info) => { if (!context.currentUser) { throw new Error("Must be logged in for this!"); } const { currentUser } = context; if (hasPermissions(currentUser.permissions, PERMISSIONS.CREATE)) { return await createEventInDb({ ...args, ...context }); } }; @samjulien

Slide 181

Slide 181 text

graphql-resolvers Lucas Constantino @samjulien

Slide 182

Slide 182 text

createEvent: combineResolvers( isAuthenticated, checkPermissions(PERMISSIONS.CREATE), async (parent, args, context, info) => { return await createEventInDb({ ...args, ...context }); } ); @samjulien

Slide 183

Slide 183 text

graphql-auth Kurt Kemple @samjulien

Slide 184

Slide 184 text

import withAuth from 'graphql-auth'; const resolvers = { Query: { users: withAuth(['users:view'], (root, args, context) => { ... }), ... } } @samjulien

Slide 185

Slide 185 text

graphql-modules Uri Goldshtein (& Many Others) @samjulien

Slide 186

Slide 186 text

import { GraphQLModule } from "@graphql-modules/core"; const MyModule = new GraphQLModule({ /*...*/ resolversComposition: { "Mutation.createEvent": [ isAuthenticated(), checkPermissions(PERMISSIONS.CREATE) ] } }); @samjulien

Slide 187

Slide 187 text

graphql-middleware Prisma Community (Matic Zavadlal) @samjulien

Slide 188

Slide 188 text

const authMiddleware = { Mutation: { createEvent: isAuthenticated }, } const server = new GraphQLServer({ typeDefs, resolvers, [authMiddleware], }) @samjulien

Slide 189

Slide 189 text

graphql-shield Matic Zavadlal @samjulien

Slide 190

Slide 190 text

No content

Slide 191

Slide 191 text

const isAuthenticated = rule({ cache: "contextual" })( async (parent, args, ctx, info) => { return ctx.user !== null; } ); const isAdmin = rule({ cache: "contextual" })( async (parent, args, ctx, info) => { return ctx.user.role === "admin"; } ); const isEditor = rule({ cache: "contextual" })( async (parent, args, ctx, info) => { return ctx.user.role === "editor"; } ); @samjulien

Slide 192

Slide 192 text

const permissions = shield({ Query: { frontPage: not(isAuthenticated), events: and(isAuthenticated, or(isAdmin, isEditor)), }, Mutation: { createEvent: isAuthenticated, }, }); const server = new GraphQLServer({ typeDefs, resolvers, middlewares: [permissions], context: (req) => ({ ...req, user: getUser(req), }), }); @samjulien

Slide 193

Slide 193 text

Models @samjulien

Slide 194

Slide 194 text

export const generateDogModel = ({ currentUser }) => ({ getAll: () => { /* logic to get all dogs */ }, getById: (id) => { /* logic to get a single dog */ }, getByGroupId: (id) => { /* logic to get a group of dogs */ }, }); @samjulien

Slide 195

Slide 195 text

getAll: () => { if(!currentUser || !currentUser.roles.includes('admin')) return null; return fetch(`${API_URL}/dog`); } @samjulien

Slide 196

Slide 196 text

Custom Directives @samjulien

Slide 197

Slide 197 text

directive @hasPermission(permission: String) on FIELD_DEFINITION @samjulien

Slide 198

Slide 198 text

type Mutation: { createEvent: Event @hasPermission(permission: PERMISSIONS.CREATE) } @samjulien

Slide 199

Slide 199 text

⚠ Couples logic to schema. 😅 Can be quite difficult. 🧪 Requires exhaustive testing. Downsides @samjulien

Slide 200

Slide 200 text

http://samj.im/graphql-auth @samjulien

Slide 201

Slide 201 text

http://samj.im/graphql-auth Thank you! @samjulien