Nextjs Auth0在getServerSideProps中获取数据

Man*_*nos 1 authentication auth0 next.js

我使用 Auth0 来验证用户身份。

我受保护的 api 路由如下:

// pages/api/secret.js

import { withApiAuthRequired, getSession } from '@auth0/nextjs-auth0';

export default withApiAuthRequired(function ProtectedRoute(req, res) {
  const session = getSession(req, res);
  const data = { test: 'test' };
  res.json({ data });
});
Run Code Online (Sandbox Code Playgroud)

我的问题是,当我尝试从 getServerSideProps 获取数据时,我收到 401 错误代码。

如果我使用 useEffect 我可以从 api 路由获取数据。

我试图像这样获取数据:

export const getServerSideProps = withPageAuthRequired({
  async getServerSideProps(ctx) {
    const res = await fetch('http://localhost:3000/api/secret');
    const data = await res.json();

    return { props: { data } };
  },
});
Run Code Online (Sandbox Code Playgroud)

我收到以下响应:错误:“not_authenticated”,描述:“用户没有活动会话或未经过身份验证”

大家有什么想法吗?谢谢!!

fel*_*osh 5

当您从getServerSideProps受保护的 API 端点调用时,您不会将任何用户的上下文(例如Cookies)传递给请求,因此,您未经过身份验证。

当您从useEffect浏览器内部运行的调用中调用时,浏览器会将所有 cookie 附加到请求,其中之一是会话 cookie。

您需要将(由浏览器)传递给getServerSidePropsAPI 调用的会话 cookie 转发。

export const getServerSideProps = withPageAuthRequired({
  async getServerSideProps(ctx) {
    const res = await fetch('http://localhost:3000/api/secret', {
      headers: { Cookie: ctx.req.headers.cookie },
// ---------------------------^ this req is the browser request to the getServersideProps
    });
    const data = await res.json();

    return { props: { data } };
  },
});
Run Code Online (Sandbox Code Playgroud)

欲了解更多信息