如何使用 Next-auth 和 firebase 将基于角色的身份验证添加到 Nextjs

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

我目前正在我的 Next.js 应用程序中使用 NextAuth.js 实现基于角色的身份验证。我已遵循 NextAuth.js 提供的文档,但在尝试将基于角色的身份验证添加到我的 API 路由时遇到错误。

我正在使用 TypeScript,我的 API 路由文件位于pages/api/auth/[..nextauth]/route.ts。

import NextAuth from "next-auth"
import CredentialsProvider from "next-auth/providers/credentials";
import {signInWithEmailAndPassword} from 'firebase/auth';
import auth from '@/app/lib/auth';


export const authOptions = {
 
  secret: process.env.AUTH_SECRET,
  pages: {
    signIn: '/signin'
  },
  session: {
    strategy: "jwt" as const,
    maxAge: 3600,
  },

  providers: [
    CredentialsProvider({
      profile(profile) {
        return {
          role: profile.role ?? "user",
        }
      },
      name: 'Credentials',
      credentials: {},
      async authorize(credentials): Promise<any> {
        return await signInWithEmailAndPassword(auth, (credentials as any).email || '', (credentials as any).password || '')
          .then(userCredential => {
            if (userCredential.user) {
              return userCredential.user;
            }
            return null;
          })
          .catch(error => (console.log(error)))
  .catch((error) => {
    console.log(error);
  });
      }
    })
  ],
  callbacks: {
    async jwt({ token, user }) {
      if (user) token.role = user.role;
      return token;
    },
    async session({ session, token }) {
      if (session?.user) session.user.role = token.role;
      return session;
    },
  },
}
const handler = NextAuth(authOptions)
export { handler as GET, handler as POST}

有人可以帮助我理解为什么会发生此错误以及如何在我的 API 路由中使用 NextAuth.js 正确实现基于角色的身份验证吗?

我尝试过的:

  • 使用 NextAuth.js 文档:我按照 NextAuth.js 文档在 Next.js 应用程序中设置基于角色的身份验证。

  • 复制代码:我从文档中复制了代码片段来实现基于角色的身份验证。

  • 遇到错误:实现代码后,遇到错误。

firebase next.js jwt next-auth role-base-authorization
1个回答
0
投票

如果您使用的是 nextjs 版本 14,您需要像这样的下一个身份验证文件路由——“pages/api/auth/[...nextauth].js”。也许这可以解决问题。

© www.soinside.com 2019 - 2024. All rights reserved.