如何使用 next-auth/authjs nextjs/13/14 按角色创建路由?

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

如何按角色保护私有路由。也就是说,如果我是用户类型“user”,我可以访问 /normal 路由,如果我是管理员,我可以访问 /admin 路由。即多个具有特定角色的私有路由,官方文档仅显示了单个路由的单个角色的示例。但我想要的是让它变得多重。

中间件.ts

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"] }

这里是从官方next-auth文档中提取的代码 https://next-auth.js.org/configuration/nextjs

我想要的是“export const config = { matcher: ['/dashboard'] }; ” 适用于该回调类型“用户”,但我想根据用户的角色创建更多受保护的路由

我正在使用nextjs 14

next.js routes roles private next-auth
1个回答
0
投票

使您的中间件适用于这两个路由,并检查您的

authorized
回调正在访问哪一个。然后根据路径解析出所需的角色。

一个非常简单的设置可能如下所示:

const AUTH_CONFIG = {
  '/admin': 'admin',
  '/normal': 'user',
};

export default withAuth(
  {
    callbacks: {
      authorized: ({ token, req }) => {
        const requiredRole = AUTH_CONFIG[req.nextUrl.pathname];
        return !requiredRole || token?.role === requiredRole;
      },
    },
  }
)

export const config = { matcher: ["/(admin|normal)"] }
© www.soinside.com 2019 - 2024. All rights reserved.