代码之家  ›  专栏  ›  技术社区  ›  Manav Kushwaha

凭据身份验证无法在NextJs应用程序路由器中使用NextAuth执行

  •  0
  • Manav Kushwaha  · 技术社区  · 1 年前

    我正在尝试在中使用自定义登录页面 NextJs 随着 NextAuth 。当我尝试登录时 NextAuth 授权功能。在前端,即使我返回也没有错误 null 或者在authorize函数内部抛出错误,即在定义时声明 NextAuthOptions

    /utils/auth.ts

    export const authOptions: NextAuthOptions = {
        pages: {
            signIn: "/login"
        },
        session: {
            strategy: "jwt"
        },
        providers : [
            GoogleProvider({
                clientId: process.env.GOOGLE_CLIENT_ID!,
                clientSecret: process.env.GOOGLE_CLIENT_SECRET!
            }),
            CredentialsProvider({
                name: "Sign In",
                credentials: {
                    username: { label: "Username", type: "text"},
                    password: { label: "Password", type: "password"}
                }, 
                async authorize(credentials) {
                    console.log("Credentials: ", credentials)
                    if (!credentials?.username || !credentials.password) {
                        throw new Error("Invalid credentials")
                    }
                    let userFromDb = await authenticateUser(credentials?.username!, credentials?.password!)
                    let returnUser = userFromDb ? {
                        id : userFromDb.id,
                        username: userFromDb.username,
                        bio: userFromDb.bio,
                        name: userFromDb.name,
                        profilePic: userFromDb.profilePic
                    } : null
    
                    return returnUser
                },
            })
        ],
    }
    

    /app/api/auth/[…nextauth]/route.ts

    const handler = NextAuth(authOptions)
    export {handler as GET, handler as POST}
    

    /应用程序/登录

      const submitData:SubmitHandler<FormSchema> = async (data: FormSchema) => {
        
        console.log("Input data:", data)
        
        const res = await signIn("credentials", {
          redirect: false,
          callbackUrl:"/",
          ...data,
        })
        console.log("response: ", res)
        if (!res?.error) {
          router.push("/")
        } else {
          console.log("Errors: ", res.error)
        }
      };
    

    前端响应:

    response {
    error: null
    ok: true
    status: 200
    url: "https://localhost:3000/api/auth/signin?csrf=true"
    }
    

    即使在authorize中抛出错误或返回null时,也会出现此响应。

    我觉得控件从未达到授权,因为它内部没有日志记录。

    我试着调试了代码,还查看了各种人的代码。似乎无法理解此错误的原因。

    0 回复  |  直到 1 年前