Auth0
withMiddlewareAuthRequired
也不会验证 api 路由。我做错了什么?
我正在使用 Next.js 13(应用程序路由器)制作一个完整的堆栈应用程序。我的应用程序文件夹中有 api 文件夹。
设置:我有这样的 middleware.ts
export default withMiddlewareAuthRequired(async function middleware(req) {
const res = NextResponse.next();
const { pathname } = req.nextUrl;
const { accessToken } = await getAccessToken(req, res);
const requestHeaders = new Headers(req.headers);
console.log(accessToken);
requestHeaders.set('Authorization', `Bearer ${accessToken}`);
const url = new URL(pathname, 'http://localhost:3000');
console.log('############ API HANDLER');
console.log(pathname);
//return res;
return NextResponse.rewrite(url, {
request: {
headers: requestHeaders,
},
});
}
);
withMiddlewareAuthRequired
的正确做法:
但是问题是:
所有 api 路由都会给出 401 错误,即使我传递了访问令牌,如上所示。 (Ui 从来不需要访问令牌,我添加它只是为了授权 api 路由,但它不起作用)。
最大的困惑:
如果用户已登录,并且当我在浏览器中访问示例 GET 端点时,它就可以工作。我可以看到 json 输出。只有在应用程序中才会出现401错误?
注意:我已在 auth0 仪表板中注册了 api,并且还传递了受众参数,因此我的访问令牌是 jwt。
注意 2:当我尝试通过邮递员并将访问令牌作为承载者传递时,它仍然给出 401 错误。
{
"error": "not_authenticated",
"description": "The user does not have an active session or is not authenticated"
}
所以我的问题是如何为我的 nextjs 13 应用程序路由器应用程序编写正确的 auth0 中间件,这样我在访问 api 路由时就不会在应用程序中收到 401 错误。
您需要使用 cookie 才能正常工作,
import { cookies } from "next/headers";
const res = await fetch(`${baseUrl}/api/<your api route>`, {
headers: { Cookie: cookie },
});
const data = await res.json();
return data;
它仅在您进行后端渲染时才有效。如果您需要在组件内进行 api 端点调用,那么您需要将其作为组件渲染的参数传递