Next.js 和 Auth0 结合使用时,获取接口请求承载的 token 主要涉及以下几个步骤:
@auth0/auth0-react
库在 Next.js 应用中集成 Auth0。import { useAuth0 } from "@auth0/auth0-react";
function MyComponent() {
const { isAuthenticated, getAccessTokenSilently } = useAuth0();
const fetchProtectedData = async () => {
if (isAuthenticated) {
try {
const token = await getAccessTokenSilently();
const response = await fetch('/api/my-protected-endpoint', {
headers: {
Authorization: `Bearer ${token}`
}
});
const data = await response.json();
console.log(data);
} catch (error) {
console.error("Error fetching protected data:", error);
}
}
};
return (
<div>
<button onClick={fetchProtectedData}>Fetch Protected Data</button>
</div>
);
}
export default MyComponent;
import { expressjwt: jwt } from "express-jwt";
import { expressJwtSecret } from "jwks-rsa";
const auth0Secret = process.env.AUTH0_SECRET;
export default function handler(req, res) {
const checkJwt = jwt({
secret: expressJwtSecret({
cache: true,
rateLimit: true,
jwksRequestsPerMinute: 5,
jwksUri: `https://your-auth0-domain/.well-known/jwks.json`
}),
audience: process.env.AUTH0_CLIENT_ID,
issuer: `https://your-auth0-domain/`,
algorithms: ["RS256"]
});
app.use(checkJwt);
// Your protected route logic here
res.status(200).json({ message: "This is a protected route" });
}
原因: JWT Tokens 通常有一个过期时间,过期后需要重新获取。
解决方法: 使用 getAccessTokenSilently
方法自动刷新 token。
原因: 可能是由于 token 不正确、过期或签名无效。
解决方法: 确保在服务器端正确配置了 JWT 验证中间件,并检查 Auth0 的设置是否正确。
原因: 浏览器安全策略阻止了跨域请求。
解决方法: 在 Next.js 中配置 CORS,并确保 Auth0 的回调 URL 和允许的 Web 源设置正确。
通过以上步骤和示例代码,你应该能够在 Next.js 和 Auth0 集成环境中成功获取和使用接口请求承载的 token。
领取专属 10元无门槛券
手把手带您无忧上云