【问题标题】:Passport.js does not authenticate SSR async requestPassport.js 不验证 SSR 异步请求
【发布时间】:2020-02-08 05:15:42
【问题描述】:

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

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

任何帮助将不胜感激!

【问题讨论】:

    标签: javascript reactjs express passport.js next.js


    【解决方案1】:

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

    TL;DR 是,如果您直接访问服务器,则直接从服务器返回您想要的数据,而不是通过对 api 的后续调用。只有当您通过客户端路由点击页面时,才应使用 api 请求。

    【讨论】:

      猜你喜欢
      • 2013-08-28
      • 1970-01-01
      • 2014-09-09
      • 2012-04-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-02-11
      相关资源
      最近更新 更多