【问题标题】:Nextjs Auth0 get data in getServerSidePropsNextjs Auth0 在 getServerSideProps 中获取数据
【发布时间】:2021-09-04 10:22:11
【问题描述】:

我正在使用 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”,描述:“用户没有活动会话或未通过身份验证”

有什么想法吗?谢谢!!

【问题讨论】:

标签: next.js auth0


【解决方案1】:

当您从 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

【讨论】:

  • 非常感谢您的回答!你可以想象我不是专业人士。我通过互联网学习。我添加了这一行,现在我开始了:TypeError: ctx.req.getHeader is not a function
  • 我将其更改为 ctx.req.headers.cookie,现在它可以工作了!非常感谢!
猜你喜欢
  • 2020-07-25
  • 1970-01-01
  • 2021-12-31
  • 1970-01-01
  • 2021-12-30
  • 2021-04-22
  • 1970-01-01
  • 2021-11-24
  • 2022-01-26
相关资源
最近更新 更多