无法在中间件nextjs中验证访问令牌

y1aodyip  于 11个月前  发布在  其他
关注(0)|答案(1)|浏览(149)

我正在尝试使用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));
        }
    }
}

字符串

mbskvtky

mbskvtky1#

问题是在其他如果block.it应该是下面的(access && request.nextUrl.pathname.startsWith('/open-bo-account'))完整的代码是这样的

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 secret_key = `${process.env.SECRET_KEY}`

    if (!access && request.nextUrl.pathname.startsWith('/open-bo-account')) {
        request.cookies.clear()
        return NextResponse.redirect(new URL('/login', request.url));

    } else if (access && request.nextUrl.pathname.startsWith('/open-bo-account')) {
        try {
            const secret = new TextEncoder().encode(secret_key);
            const decodedToken = await jwtVerify(access, secret);
            console.log(decodedToken)
            // const payload = decodedToken.payload;
            if (decodedToken) {
                return NextResponse.next();
            }
        }catch (error) {
            request.cookies.clear();
            return NextResponse.redirect(new URL('/login', request.url));
        }
    }
}

字符串

相关问题