【问题标题】:Next JS API calls with auth0接下来使用 auth0 调用 JS API
【发布时间】:2021-06-18 16:37:21
【问题描述】:

我有一个关于 auth0next js 的问题。

例如,我有下一个代码(此代码有效)

//initialprops enables server-side rendering in a page and allows you to do initial data population
ModelsList.getInitialProps = async (ctx) => {
  //this is static token to test from auth0.com
  const accessToken = 'eyJhbG.....'
  //fetching data
  const res = await fetch('http://localhost:7071/api/bo/getModels', {
   headers: {
    Authorization: `Bearer ${accessToken}`
   }
  })
    
  const json = await res.json()
   
  return { data: json }
}

如您所见,我将 accessToken 变量作为文本。这对我来说是个问题

如何让accessToken动态化?

非常感谢!

P.S 请不要参考 auth0 文档,我已经尝试了很多。请提供一个真正的解决方案/示例。

【问题讨论】:

  • 如果你要让它动态化,accessToken 从哪里来?
  • 真的不知道,在文档中他们有这个例子:github.com/auth0/nextjs-auth0/blob/main/examples/… 但是如果你测试例子,你有对象错误(无法处理响应)。你能举一些例子吗?
  • 请记住,您的代码在 getInitialProps 内运行 - 它可以在服务器和客户端上运行 - 而您链接的示例位于始终发生在服务器上的 API 路由中。您可能想尝试改用getServerSideProps

标签: next.js auth0


【解决方案1】:

好的,这对我有用。

假设你有api.example.com/resources。这是数据实际所在的位置。您需要通过 next 的 api 进行代理。

在你的 jsx 组件中,你获取 next 的 api。

// components/Dashboard.jsx

const API_URL = "api/resources"; 

async function fetcher(url: any) {
  const res = await fetch(url);
  const json = await res.json();
  return json;
}

function Dashboard() {
  const { data, error } = useSWR(API_URL, fetcher);

  if (error) return <div>failed to load</div>;
  if (!data) return <div>loading...</div>;

  return <div>show your resources here</div>;
}

现在在 next 的 api 文件中,您可以获取您需要的实际端点。

// api/resources.js
import {
  getAccessToken,
  getSession,
  withApiAuthRequired,
} from "@auth0/nextjs-auth0";

export default withApiAuthRequired(async function healthcheck(req, res) {
  const session = await getSession(req, res);
  const token = session?.idToken;

  const response = await fetch("https://api.example.com/resources", {
    method: "GET",
    headers: {
      Authorization: `Bearer ${token}`,
    },
  });
  const data = await response.json();
  res.status(200).json(data);
});

如果您遇到错误,请检查您获得的 jwt。受众或范围不匹配错误通常是罪魁祸首。

【讨论】:

    猜你喜欢
    • 2019-12-11
    • 2021-12-04
    • 2020-04-25
    • 2022-12-25
    • 2019-11-20
    • 2022-06-11
    • 2021-09-05
    • 2021-01-01
    • 2022-10-11
    相关资源
    最近更新 更多