next.js - 接下来使用 auth0 调用 JS API
问题描述
我有一个关于auth0和next 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文档,我已经尝试了很多。请提供一个真正的解决方案/示例。
解决方案
好的,所以这对我有用。
假设你有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。受众或范围不匹配错误通常是罪魁祸首。
推荐阅读
- javascript - tbody 元素的意外自动插入:表不是 row.parentElement
- javascript - 'this' 未定义 - ReactJS
- java - 调用 restTemplate.exchange() 时出现 IllegalStateException
- reactjs - 如何将 React + TypeScript 中的道具从父组件传递给子组件?
- android - 我可以在 MPAndroidChart 中设置单位吗?
- java - 为什么 Calendar.getTimeInMillis() 返回负值?
- java - 在 Spring JPA/Boot 中传播和持久化树中的更改
- node.js - 使用快速护照和sequelize的电子邮件验证
- html - How to style and change the width of the google translate element
- c# - 如何更改以上页面中的对象