初始情况:我有两个名为accessToken和refreshToken的服务器端cookie(httponly)。有效载荷如下:
{
"user":{
"firstname":"John",
"lastname":"Doe",
"roles":[
"accounting",
"supporter"
]
}
}
目标:使用Next.js 13(基于应用程序文件夹)处理服务器端授权。某些路由应该受到保护,并且只能由具有特定角色的某些用户访问。
示例:
- 每个人都应该可以访问GET/login
- 仅针对授权用户的GET/仪表板
- GET/accounting仅适用于具有accounting角色的用户
- GET/admin仅适用于具有admin角色的用户
您可以编写一个中间件。在next13中,中间件文件与package.json在同一目录中,并且应该是middleware.js
(或.ts)
export async function middleware(req: NextRequest, res: NextResponse) {
// get all the cookies
let cookies = req.cookies.getAll();
// read those cookies. based on cookies you decide which paths can be visited
const isAuthorized="define logic if the the user authorized"
console.log("req.pathname", req.nextUrl.pathname);
const currentPath = req.nextUrl.pathname;
if (currentPath==="/dashboard" && isAuthorized ){
// you allow the user to visit this page
return NextResponse.next()
}
// similarly add logic for other cases
}