【问题标题】:How to make simple protected route using nextAuth?如何使用 nextAuth 制作简单的受保护路由?
【发布时间】:2022-10-01 12:52:34
【问题描述】:

我想做简单的受保护路线。

我有凭据提供程序和 nextAuth 中间件。我只想做简单的逻辑:

  • 如果用户已登录,他可以访问 /profile,如果他访问 /signup 或 /signin,则将他重定向到 /profile,如果他未登录,则无法访问 /profile 并将他重定向到 /signin
  • 有些路线是中立的——例如他可以在登录或未登录时访问/shop。

有我的 [...nextauth].ts

export default NextAuth({
    session: {
        strategy: \'jwt\',
    },
    providers: [
        CredentialsProvider({
            type: \'credentials\',
            async authorize(credentails) {
                const { password, email } = credentails as Signin

                try {
                    const client = await connectToDatabase()
                    if (!client) return

                    const db = client.db()

                    const user = await existingUser(email, db)

                    if (!user) throw new Error(\'Invalid credentails!\')

                    const isPasswordCorrect = await verifyPassword(password, user.password)

                    if (!isPasswordCorrect) throw new Error(\'Invalid credentails!\')

                    return { email: user.email, name: user.name, id: user._id.toString() }
                } catch (e: unknown) {
                    if (e instanceof Error) {
                        throw new Error(e.message)
                    }
                }
            },
        }),
    ],
})

    标签: reactjs authentication next.js routes next-auth


    【解决方案1】:

    写一个中间件

    const authorizedRoles = (...roles) => {
      return (req, res, next) => {
        if (!roles.includes(req.user.role)) {
          return next(
            // write logic to handle errors
            new ErrorHandler(
              `Role (${req.user.role}) is not allowed to access this resource.`,
              403
            )
          );
        }
    
        next();
      };
    };
    

    那么无论你想保护哪条路由,都使用这个中间件。然后在受保护页面的getServerSideProps

    export async function getServerSideProps(context) {
      const session = await getSession({ req: context.req });
    
      if (!session || session.user.role !== "admin") {
        return {
          redirect: {
            destination: "/home",
            // permanent - if `true` will use the 308 status code which instructs clients/search engines to cache the redirect forever.
    
            permanent: false,
          },
        };
      }
    
      return {
        props: {},
      };
    }
    

    【讨论】:

      【解决方案2】:

      除了其他答案之外,您可以做的是-

      1. 在登录和注册时安装组件时,检查用户是否经过身份验证。如果经过认证。使用 router.push 进行配置,否则在登录/注册时。

      2. 在配置文件中再次检查组件安装时的身份验证,如果不是,则验证推送以登录,否则在配置文件中。这里重要的是在检查用户是否经过身份验证之前不要显示配置文件页面的布局和内容。使用 spiner 或 loader 直到进行身份验证检查。

      【讨论】:

        猜你喜欢
        • 2021-04-06
        • 2022-11-16
        • 1970-01-01
        • 2021-05-23
        相关资源
        最近更新 更多