首页 > 解决方案 > 接下来使用 auth0 调用 JS API

问题描述

我有一个关于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动态化?

非常感谢!

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

标签: next.jsauth0

解决方案


好的,所以这对我有用。

假设你有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>;
}

现在在下一个 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);
});

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


推荐阅读