【问题标题】:set current user in context using apollo server使用 apollo 服务器在上下文中设置当前用户
【发布时间】:2018-08-29 18:47:27
【问题描述】:

我有这个中间件,需要让当前用户在 apollo 服务器的上下文中设置它

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


 }
 next()

   })

并且需要在上下文中设置当前用户

  const SERVER = new ApolloServer({
      schema,
      context:{
          currentUser //need to set this current user
         }
  })


   SERVER.applymiddleware({app})

【问题讨论】:

    标签: reactjs graphql apollo


    【解决方案1】:

    Apollo 服务器中的上下文 api 提供如下处理请求

    const initGraphQLserver = () => {
      const graphQLConfig = {
        context: ({ req, res }) => ({
          user: req.user,
        }),
        rootValue: {},
        schema,
      };
    
      const apolloServer = new ApolloServer(graphQLConfig);
      return apolloServer;
    };
    

    这将假定您将拥有可以解析 cookie 或标头的适当中间件。这取决于您的身份验证机制,因为您之前需要在某些中间件中为请求设置用户,如果您想使用 JWT,您可以使用例如这个中间件

    const auth = (req, res, next) => {
      if (typeof req.headers.authorization !== 'string') {
        return next();
      }
    
      const header = req.headers.authorization;
      const token = header.replace('Bearer ', '');
      try {
        const jwtData = jwt.verify(token, JWT_SECRET);
        if (jwtData && jwtData.user) {
          req.user = jwtData.user;
        } else {
          console.log('Token was not authorized');
        }
      } catch (err) {
        console.log('Invalid token');
      }
      return next();
    };
    

    如果 jwt 令牌正确,此中间件将注入用户,然后在您的服务器文件中,您将需要具有以下中间件顺序

    const app = express();
    
    app.use(auth);
    
    initGraphQLserver().applyMiddleware({ app });
    

    现在您的架构上下文中应该有用户。我希望清楚,代码没有完成,但应该很容易完成所有事情。

    【讨论】:

    • @mu_ali7963 这对你有用吗?如果是的话,需要你的帮助来解决我现在所处的相同场景......
    • 对不起,很长一段时间没有响应,您可以使用 context: req => ({...req}) 并验证您的令牌并将 userId 像这样 req.userId = userId
    猜你喜欢
    • 2018-02-11
    • 2023-02-25
    • 2017-02-07
    • 1970-01-01
    • 2019-04-27
    • 1970-01-01
    • 2019-07-23
    • 2017-05-25
    • 2020-03-29
    相关资源
    最近更新 更多