2

我目前正在使用 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.

我怎样才能设置阿波罗服务器 - 用这个表达?

4

1 回答 1

2

您可以在 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}`));

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

于 2018-07-27T15:25:28.223 回答