Setting up auth0 with apollo server

938 views Asked by At

I am currently using apollo with express. Now I want to add auth0 to the resolvers but could not find docs about it (altought, graphcool is using it). Normally, you do the following in node:

const checkJwt = jwt({
  // Dynamically provide a signing key
  // based on the kid in the header and 
  // the singing keys provided by the JWKS endpoint.
  secret: jwksRsa.expressJwtSecret({
    cache: true,
    rateLimit: true,
    jwksRequestsPerMinute: 5,
    jwksUri: `https://YOUR_AUTH0_DOMAIN/.well-known/jwks.json`
  }),

  // Validate the audience and the issuer.
  audience: '{YOUR_API_IDENTIFIER}',
  issuer: `https://YOUR_AUTH0_DOMAIN/`,
  algorithms: ['RS256']
});

then you add:

app.use(checkJwt)

and your api's roots are secured waiting for the access_token.

How can I set up apollo server - express with this?

1

There are 1 answers

0
Jose Ángel de Pascual Viciana On

You can add checkJwt before Apollo Server. An example:

const { ApolloServer, gql } = require('apollo-server-express');
const express = require('express');
const app = express();
const jwt = require('express-jwt');
const jwksRsa = require('jwks-rsa');
const cors = require('cors');
const fs = require('fs');
const resolvers = require('./data/resolvers').resolvers;
const typeDefs = gql(fs.readFileSync('./data/schema.graphql', 'utf8'));

// Enable CORS
app.use(cors());

//jwtCheck
const checkJwt = jwt({
    // Dynamically provide a signing key based on the kid in the header and the singing keys provided by the JWKS endpoint
    secret: jwksRsa.expressJwtSecret({
        cache: true,
        rateLimit: true,
        jwksRequestsPerMinute: 5,
        jwksUri: `https://YOUR_AUTH0_DOMAIN/.well-known/jwks.json`
    }),

    // Validate the audience and the issuer
    audience: '{YOUR_API_IDENTIFIER}', //replace with your API's audience, available at Dashboard > APIs
    issuer: 'https://YOUR_AUTH0_DOMAIN/',
    algorithms: [ 'RS256' ]
});

app.use(checkJwt);

//Apollo Server
const server = new ApolloServer({ typeDefs, resolvers,
    context: ({ req }) => {
        const user = req.user;
        return { user };
    }
});

server.applyMiddleware({ app });

app.listen({ port: 4000 }, () => console.log(`  Server ready at http://localhost:4000${server.graphqlPath}`));

In this example, decoded token is passed to resolvers in the context.