我正在开发一个应用程序,前端使用 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?
任何指导或建议将不胜感激。预先感谢您。