|
| 1 | +import express from 'express' |
| 2 | +import { ApolloServer, gql } from 'apollo-server-express' |
| 3 | +import { configureKeycloak } from '../lib/common' |
| 4 | +import cors from "cors" |
| 5 | +import { |
| 6 | + KeycloakContext, |
| 7 | + KeycloakTypeDefs, |
| 8 | + KeycloakSchemaDirectives |
| 9 | +} from '../../dist/index' |
| 10 | + |
| 11 | +const app = express() |
| 12 | + |
| 13 | +const graphqlPath = '/graphql' |
| 14 | + |
| 15 | +// perform the standard keycloak-connect middleware setup on our app |
| 16 | +const { keycloak } = configureKeycloak(app, graphqlPath) |
| 17 | + |
| 18 | +// Ensure entire GraphQL Api can only be accessed by authenticated users |
| 19 | +app.use(graphqlPath, keycloak.protect()) |
| 20 | +app.use(cors()); |
| 21 | +const typeDefs = ` |
| 22 | + type Query { |
| 23 | + hello: String @hasRole(role: "developer") |
| 24 | + } |
| 25 | +` |
| 26 | + |
| 27 | +const resolvers = { |
| 28 | + Query: { |
| 29 | + hello: (obj, args, context, info) => { |
| 30 | + // log some of the auth related info added to the context |
| 31 | + console.log(context.kauth.isAuthenticated()) |
| 32 | + console.log(context.kauth.accessToken.content.preferred_username) |
| 33 | + |
| 34 | + const name = context.kauth.accessToken.content.preferred_username || 'world' |
| 35 | + return `Hello ${name}` |
| 36 | + } |
| 37 | + } |
| 38 | +} |
| 39 | + |
| 40 | +const server = new ApolloServer({ |
| 41 | + typeDefs: [KeycloakTypeDefs, typeDefs], |
| 42 | + // See https://github.com/ardatan/graphql-tools/issues/1581 |
| 43 | + schemaDirectives: KeycloakSchemaDirectives, |
| 44 | + resolvers, |
| 45 | + context: ({ req }) => { |
| 46 | + return { |
| 47 | + kauth: new KeycloakContext({ req : req as any }) |
| 48 | + } |
| 49 | + } |
| 50 | +}) |
| 51 | + |
| 52 | +server.applyMiddleware({ app }) |
| 53 | + |
| 54 | +const port = 4000 |
| 55 | + |
| 56 | +app.listen({ port }, () => |
| 57 | + console.log(`🚀 Server ready at http://localhost:${port}${server.graphqlPath}`) |
| 58 | +) |
0 commit comments