使用apollo服务器设置auth0

时间:2017-09-02 14:58:50

标签: javascript express auth0 apollo-server

我目前正在使用apollo和express。现在我想将auth0添加到解析器但是找不到关于它的文档(altought,graphcool正在使用它)。通常,您在节点中执行以下操作:

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']
});

然后你添加:

app.use(checkJwt)

并确保您的api的根等待access_token

如何设置apollo服务器 - 用此表达?

1 个答案:

答案 0 :(得分:1)

您可以在Apollo Server之前添加checkJwt。一个例子:

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}`));

在此示例中,已解码的令牌在上下文中传递给解析器。