【问题标题】:How to authenticate user based on cookie?如何根据 cookie 对用户进行身份验证?
【发布时间】:2021-11-02 12:50:03
【问题描述】:

我已将我的 Apollo 客户端和服务器配置为使用 cookie:

客户:

  const httpLink = createHttpLink({
    uri: 'http://localhost:9090/graphql',
    credentials: 'include',
  });

  const cache = new InMemoryCache();

  const client = new ApolloClient({
    link: httpLink,
    cache,
  });

服务器:

  const app = express();
  const server = new ApolloServer({
    resolvers,
    typeDefs,
    context: async ({req, res}) => ({
      req,
      res,
      prisma,
    }),
  });
  await server.start();

  const corsOptions = {
    origin: 'http://localhost:8080',
    credentials: true,
  };

  app.use(cors(corsOptions));
  app.use(express.urlencoded({
    extended: true,
  }));
  server.applyMiddleware({
    app, cors: corsOptions,
  });

  app.listen({port: 9090}, () =>
    console.log(`???? Server ready at http://localhost:9090${server.graphqlPath}`),
  );

登录解析器:

  loginUser: async (_, args, {req, res}) => {
    const theUser = await prisma.user.findUnique({
      where: {email: String(args.email)},
    });
    if (!theUser) throw new Error('Unable to Login');
    const isMatch = bcrypt.compareSync(args.password, theUser.password);
    if (!isMatch) throw new Error('Unable to Login');

    const token = jwt.sign(theUser, 'supersecret');

    res.cookie('id', token, {
      httpOnly: true,
      secure: process.env.NODE_ENV === 'production',
      maxAge: 1000 * 60 * 60 * 24 * 7,
    });

    return true;
  },

当我登录我的 React 应用程序时,服务器会按预期设置一个 cookie,但我不确定如何使用该客户端 cookie 在服务器中验证我的用户以及如何保持登录状态。 cookie 也会添加到请求中。

这是一个仅限 http 的 cookie,所以我不能在客户端使用 cookie 信息。所以我想我需要一个函数来在每次加载应用程序时查询登录突变,然后在服务器上我可以检查请求,如果它在请求 cookie 中有 JWT 令牌,我可以对用户进行身份验证。

但我希望得到有关这种方法的一些反馈。

【问题讨论】:

    标签: authentication cookies jwt apollo


    【解决方案1】:

    根据您的登录解析器,cookie 应该包含在 req 的 cookie 数组中(您可能会考虑比“id”更独特的 cookie id,并且应该从 env 文件中提取秘密)。您可以将此中间件添加到您的服务器,以检查和验证每个请求的 cookie:

    app.use((req, use, next) => {
        const { id } = req.cookies;
        if (id) {
            const { user } = jwt.verify(
                id,
                process.env.SUPERSECRET
            );
            // put the user onto the req for future requests to access
            req.user = user;
        }
        next();    
    });
    

    您可以只包含用户的 id,而不是将整个用户放在 cookie 上,然后添加另一个中间件,以便在每次请求时使用该 id 查询用户的数据。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-12-04
      • 1970-01-01
      • 2017-05-06
      • 1970-01-01
      • 2015-02-21
      • 2021-07-26
      • 1970-01-01
      相关资源
      最近更新 更多