Nextjs Auth0 在 getServerSideProps 中获取数据

时间:2021-06-20 13:15:40

标签: next.js auth0

我使用 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 });
});

我的问题是当我尝试从 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 } };
  },
});

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

有什么想法吗?谢谢!!

1 个答案:

答案 0 :(得分:0)

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

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

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

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 } };
  },
});

对于more info