Next.js 中间件无法使用不同域访问生产中的 JWT Cookies

问题描述 投票:0回答:1

我正在开发一个应用程序,前端使用 Next.js,后端使用 Express.js 开发 Node.js。我在 Next.js 中使用中间件进行基于 JWT 的身份验证。在我的本地开发环境中,前端和后端都在 localhost 上运行,但在不同的端口上(前端在 http://localhost:3000 上,后端在 http://localhost:8001 上),一切都按预期运行。

但是,在生产中部署时,我的前端位于 https://frontend.com ,后端位于 https://backend.com:8001 。在这种环境中,中间件无法访问 cookie 中存储的 JWT 令牌,从而阻止正确的身份验证和授权。

这是我的 Next.js 中间件的相关代码:

// next.js middleware
import { NextResponse } from "next/server";
import { jwtVerify } from "jose";
// ... other imports ...

const secret = process.env.SECRET;

async function verify(token, secret) {
    const { payload } = await jwtVerify(token, new TextEncoder().encode(secret));
    return payload;
}

export default async function middleware(request) {
    const url = request.url;
    const nextUrl = request.nextUrl.clone();
    // ... middleware logic ...

    // Example function for verifying access
    const checkAccess = async (allowedRole) => {
        const jwt = request.cookies.get('token')?.value;
        if (!jwt) {
            nextUrl.pathname = '/';
            return NextResponse.rewrite(nextUrl);
        }
        
        try {
            const verification = await verify(jwt, secret);
            if (verification.Role === allowedRole) {
                return NextResponse.next();
            } else {
                throw new Error("ACCESS DENIED");
            }
        } catch (e) {
            // Error handling
            // ...
        }
    };

    // Role verification
    if (url.includes("/dashboard/teacher")) {
        return checkAccess('Teacher');
    }
    // ... other verifications ...
};

return NextResponse.next();


This is the cookie configuration for the login on the backend:

function getDomainURL(){
    switch (process.env.NODE_ENV){
        case ('production'):
            return '.frontend.com';
        case ('development'):
            return 'localhost'
    }
}

const COOKIE_OPTIONS = {
    httpOnly: true,
    path: "/",
    sameSite: 'None', // Permitir cookies en solicitudes entre diferentes orígenes
    secure: true, // Requerido cuando sameSite es 'None'
    domain: getDomainURL()
};

 res.setHeader("Set-Cookie", serialize("token", token, COOKIE_OPTIONS));

function getOriginURL(){
    switch (process.env.NODE_ENV){
        case ('production'):
            return 'https://www.frontend.com';
        case ('development'):
            return 'http://localhost:3000'
    }
}

let originURL = getOriginURL()

app.use(cors({
    origin: originURL,
    credentials: true,
}))

当后端位于域https://backend.com:8001时,中间件无法访问cookie中的令牌。这会阻止中间件正常运行以保护路由。

如何配置我的 Next.js 应用程序和/或后端,以便中间件即使位于不同的域也可以正确访问 cookie?

任何指导或建议将不胜感激。预先感谢您。

cookies middleware next.js13
1个回答
0
投票

我相信您将无法通过您的请求访问 cookie,因为域不同。

这是一个发生相反情况的场景,但它也适用于您的情况。

访问后端在另一个域上设置的cookie

问候!

© www.soinside.com 2019 - 2024. All rights reserved.