Passport.js 不验证 SSR 异步请求

Passport.js does not authenticate SSR async request

我已经使用 local-stratagey 和我的快速服务器设置 Passport.js

当我登录并在 NextJS 的 getInitialProps 中发出异步请求时,它正确地允许通过客户端渲染而不是服务器端渲染的 GET 请求。也就是说,如果我通过客户端路由访问私有路由,它会显示路由并允许 aync 请求,但是当我直接从浏览器访问页面时,它允许路由但不允许通过服务器端的异步请求getInitialProps.

的调用

为了增加复杂性,我正在使用 Next.js 并且它是新的 api 路线。我首先在 server.js 中捕获路由以进行身份​​验证,然后如果通过身份验证,我将其传递给 Next.

  // server.js routes
  app.get('/apples', function(req, res) {
    if (req.isAuthenticated()) {
      console.log(`[${req.method}]`, 'SERVER - ROUTE AUTHENTICATED');
      return handle(req, res);
    } else {
      console.log(`[${req.method}]`, 'SERVER - ROUTE NOT AUTHENTICATED');
      res.redirect("/login");
    }
  });

  app.get('/api/apples', function(req, res) {
    if (req.isAuthenticated()) {
      console.log(`[${req.method}]`, 'SERVER - API AUTHENTICATED');
      return handle(req, res);
    } else {
      console.log(`[${req.method}]`, 'SERVER - API NOT AUTHENTICATED');
      res.status(401).end();
    }
  });

// /pages/apples.js - the consuming page
Apples.getInitialProps = async () => {
  const response = await fetch('http://localhost:3000/api/apples');
  const apples = await response.json();
  return { apples }
}

如有任何帮助,我们将不胜感激!

这个帖子解决了我的问题:https://spectrum.chat/next-js/general/halp-nextjs-express-passport-next-api-routes~f5f60d4a-cfea-422b-8dfe-ed243b598ce6

TL;DR 是,如果您直接访问服务器,return 您想要的数据直接来自服务器,而不是通过后续调用 api。 api 请求只能在您通过客户端路由访问页面时使用。