提问人:Mohammed Ghazwan Almilhim 提问时间:9/27/2023 最后编辑:Mohammed Ghazwan Almilhim 更新时间:9/27/2023 访问量:79
身份验证后如何使用 NextAuth 和中间件保护特定页面
How to secure specific pages using NextAuth and Middleware after authentication
问:
在使用中间件和 NextAuth 进行身份验证后,我无法保护 Next.js 应用程序中的特定页面。
在用户登录之前,页面将受到保护,此时它们将变得可见。但是,登录后,我不想向具有“USER”角色的用户显示 /dashboard 页面,也不想向具有“ADMIN”角色的用户显示 /booking 页面。此外,我不想在登录后显示主页 (/) 或 /signup 页面。
这是我使用的代码:
import { withAuth } from 'next-auth/middleware';
export default withAuth({
callbacks: {
authorized: (params) => {
let { token } = params;
return !!token;
},
},
});
export const config = {
matcher: ["/dashboard/:path*", "/booking/:path*", "/settings/:path*"]
};
我尝试将中间件函数与if语句一起使用,例如:
import { NextResponse } from 'next/server';
import { withAuth } from 'next-auth/middleware';
export default withAuth(
function middleware(req) {
if (req.nextUrl.pathname.startsWith("/") && req.nextauth.token?.role === "USER") {
const url = req.nextUrl.clone();
url.pathname = "/booking";
return NextResponse.redirect(url);
}
if (req.nextUrl.pathname.startsWith("/") && req.nextauth.token?.role === "ADMIN") {
const url = req.nextUrl.clone();
url.pathname = "/dashboard";
return NextResponse.redirect(url);
}
if (req.nextUrl.pathname.startsWith("/signup") && req.nextauth.token?.role === "USER") {
const url = req.nextUrl.clone();
url.pathname = "/booking";
return NextResponse.redirect(url);
}
if (req.nextUrl.pathname.startsWith("/signup") && req.nextauth.token?.role === "ADMIN") {
const url = req.nextUrl.clone();
url.pathname = "/dashboard";
return NextResponse.redirect(url);
}
if (req.nextUrl.pathname.startsWith("/dashboard") && req.nextauth.token?.role === "USER") {
const url = req.nextUrl.clone();
url.pathname = "/booking";
return NextResponse.redirect(url);
}
if (req.nextUrl.pathname.startsWith("/booking") && req.nextauth.token?.role === "ADMIN") {
const url = req.nextUrl.clone();
url.pathname = "/dashboard";
return NextResponse.redirect(url);
}
},
{
callbacks: {
authorized: (params) => {
let { token } = params;
return !!token;
},
},
}
);
export const config = {
matcher: ["/dashboard/:path*", "/booking/:path*", "/settings/:path*"]
};
根据文档:“只有当授权回调返回 true 时,才会调用中间件函数。
文档中的代码:
import { withAuth } from "next-auth/middleware"
export default withAuth(
// `withAuth` augments your `Request` with the user's token.
function middleware(req) {
console.log(req.nextauth.token)
},
{
callbacks: {
authorized: ({ token }) => token?.role === "admin",
},
}
)
export const config = { matcher: ["/admin"] }
但是,它似乎没有按预期工作。谁能指导我如何使用中间件和 NextAuth 正确保护特定路由?
答: 暂无答案
评论