javascript - 使用 apollo 服务器设置 auth0

标签 javascript express auth0 apollo-server

我目前正在使用 apollo 和 express。现在我想将 auth0 添加到解析器,但找不到关于它的文档(当然,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 服务器 - express?

最佳答案

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

在这个例子中,解码后的 token 被传递给上下文中的解析器。

关于javascript - 使用 apollo 服务器设置 auth0,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46015074/

相关文章:

javascript - 在 Jquery 中选择带有标题的元素

Node.js 和 express - 如何读取 cookie 但未定义

node.js - MEAN 堆栈安装给出 304 和 404s

graphql - 如何在 Graphql 架构级别检查 AWS AppSync OIDC 指令的角色或权限

javascript - 如何在按钮中隐藏 API 连接

javascript - 为什么用 document.write() 写 <script> 标签时要拆分它?

node.js - 如何查看 JWT 中存储的数据?使用 auth0 和express-jwt

javascript - 最初隐藏一个 div 以供以后显示

javascript - 如何在javascript中动态增加变量名称?