我正在尝试使用jose库在nextjs中间件中验证我的token。但是如果代码进入catch块,它将进入无限循环,并且不会重定向到登录页面。实际上,我以前从未验证过token,所以我有点困惑我现在应该做什么。这个问题特别发生在有人在浏览器中更改访问令牌时。这是我的代码。
import { NextResponse } from "next/server";
import type { NextRequest } from "next/server";
import { jwtVerify } from 'jose';
export default async function middleware(request: NextRequest) {
const access = request.cookies.get("access")?.value;
const url = request.url;
const urlStartWithUrl = `${process.env.NEXT_PUBLIC_HOST_FRONTEND}/open-bo-account`;
const redirectUrl = `${process.env.NEXT_PUBLIC_HOST_FRONTEND}/login/`;
if (!access && request.nextUrl.pathname.startsWith('/open-bo-account')) {
request.cookies.clear()
return NextResponse.redirect(new URL('/login', request.url));
} else if (access) {
try {
const secret = new TextEncoder().encode(
"secret key"
);
const decodedToken = await jwtVerify(access, secret);
if (decodedToken) {
return NextResponse.next();
}
request.cookies.clear();
return NextResponse.redirect(new URL('/login', request.url));
} catch (error) {
const cookiesBeforeClear = request.cookies.getAll();
console.log("Cookies before clear:", cookiesBeforeClear);
request.cookies.clear();
const cookiesAfterClear = request.cookies.getAll();
console.log("Cookies after clear:", cookiesAfterClear);
return NextResponse.redirect(new URL('/login', request.url));
}
}
}
字符串
1条答案
按热度按时间mbskvtky1#
问题是在其他如果block.it应该是下面的
(access && request.nextUrl.pathname.startsWith('/open-bo-account'))
完整的代码是这样的字符串