首页 > 解决方案 > 如何验证来自 Localstorage 的令牌并将 currentUser 从 Apollo Server 返回到 React 前端?

问题描述

我已经有一个 jwt 中间件,它验证令牌并将 currentUser 返回到 React 前端:

app.use(async (req, res, next) => {
    const token = req.headers['authorization'];
    if(token !== "null") {
        try{
            const currentUser = await jwt.verify(token, process.env.SECRET)
        } catch {
        console.error(err);
    }
}
next();
});

现在,我想将逻辑集成到以下 Apollo 服务器中:

const app = express();
const server = new ApolloServer({
  typeDefs: gql(typeDefs),
  resolvers,
  context: async () =>({ 
  db,
  secret: process.env.SECRET,
  }),
});

app.use(cors(corsOptions));
server.applyMiddleware({ app });

最后, currentUser 的值应该可以在反应前端使用。
我怎样才能做到这一点?

标签: javascriptauthenticationjwtgraphqlapollo

解决方案


您可以将 添加currentUserrequest中间件内的对象中。接下来,您将其从请求中复制到 GraphQL 上下文中。然后您可以添加一个currentUser解析器并简单地从上下文中返回用户。

你的中间件

app.use(async (req, res, next) => {
    const token = req.headers['authorization'];
    if(token !== "null") {
        try{
            req.currentUser = await jwt.verify(token, process.env.SECRET)
        } catch {
        console.error(err);
    }
}
next();
});

你的服务器

const app = express();
const server = new ApolloServer({
  typeDefs: gql(typeDefs),
  resolvers,
  context: ({ req }) =>({ 
    currentUser: req.currentUser,
    db,
    secret: process.env.SECRET,
  }),
});

app.use(cors(corsOptions));
server.applyMiddleware({ app });

和解析器

const resolvers = {
  Query: {
    currentUser: (parent, args, context) => context.currentUser,
    ...
  }
}

添加相应的类型定义,您应该能够从您的客户端查询当前用户。

如果您需要更多信息,这里有一个可能会有所帮助的详细教程。


推荐阅读