我在我的下一个项目中使用Next-auth凭据,但next-auth/react中的signIn()似乎不能正常工作.无论登录信息是否正确,我都会被重定向到管理页面.

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

这里有一些信息

应用程序/组件/表单/SignInForm.tsx

'use client';


import { useRouter } from 'next/navigation';
import { redirect } from 'next/dist/server/api-utils';
import { signIn } from 'next-auth/react'; // Fixed import




const SignInForm = () => {

  const router  = useRouter();

  const form = useForm<z.infer<typeof FormSchema>>({
    resolver: zodResolver(FormSchema),
    defaultValues: {
      email: '',
      password: '',
    },
  });

  const onSubmit = async (values: z.infer<typeof FormSchema>) => {

    try {
      // I have verified that values.email and values.password are correct!
      // I think that signIn is where the problem is!
      const signInData = await signIn("credentials", {
        email: values.email,
        password: values.password,
        redirect: false,
      });

      if(signInData?.error) {
        console.log(signInData.error)
      } else{
        router.push("/admin");
      }
    } catch (error) {
      console.error("Error signing in:", error);
    }
  }
   

  return (
    <Form {...form}>
      <form onSubmit={form.handleSubmit(onSubmit)} className='w-full'>
        <div className='space-y-2'>
          <FormField
            control={form.control}
            name='email'
            render={({ field }) => (
             
                  <Input placeholder='mail@example.com' {...field} />
                
            )}
          />
          <FormField
            control={form.control}
            name='password'
            render={({ field }) => (
             
                  <Input
                    type='password'
                    placeholder='Enter your password'
                    {...field}
                  />
                
            )}
          />
        </div>
        <Button className='w-full mt-6' type='submit'>
          Sign in
        </Button>
      </form>
      
      
    </Form>
  );
};

export default SignInForm;

App/api/auth/[...nextauth]/route.ts

import NextAuth from "next-auth";
import { authOptions } from "@/lib/auth";

const handler = NextAuth(authOptions)

export { handler as GET, handler as POST}

app/lib/auth.ts

import { NextAuthOptions } from "next-auth";
import CredentialsProvider from "next-auth/providers/credentials";
import { PrismaAdapter } from "@next-auth/prisma-adapter"
import { db } from "./db";

export const authOptions: NextAuthOptions = {
  adapter: PrismaAdapter(db),
  session: {
    strategy: 'jwt'
  },
  pages: {
    signIn: '/sign-in'
  },

  providers: [
    CredentialsProvider({
      name: "credentials",
    
      credentials: {
        email: { label: "Username", type: "text", placeholder: "jsmith" },
        password: { label: "Password", type: "password" }
      },
      async authorize(credentials) {
        // removing logic to see why I am still being redirected
        return null
      }
    })
  ]

}

我不确定为什么我仍然被重定向到/admin,尽管我清楚地在Auth.ts上放了return null.任何帮助都将不胜感激.

推荐答案

我没有看到SessionProvider正在包装你的应用程序.这就是signIn函数不能与authorize通信的原因

RootLayout

"use client";


import { SessionProvider } from 'next-auth/react';

export default function RootLayout({
  children,
}: {
  children: React.ReactNode;
}) {
  return (
    <html lang="en">
      <body className={inter.className}>
        <SessionProvider>
          <main className="h-screen flex flex-col justify-center items-center">
            <Navbar />
            {children}
          </main>
        </SessionProvider>
      </body>
    </html>
  );
}

Javascript相关问答推荐

如何通过在提交时工作的函数显示dom元素?

为什么从liveWire info js代码传递数组我出现错误?

为什么ngModel不能在最后一个版本的Angular 17上工作?'

如何从一个列表中创建一个2列的表?

如何调用名称在字符串中的实例方法?

在Three JS中看不到补间不透明度更改效果

如何在JavaScript文件中使用Json文件

为什么useState触发具有相同值的呈现

使用Nuxt Apollo在Piniastore 中获取产品细节

Reaction组件在本应被设置隐藏时仍显示

TypeError:无法读取未定义的属性(正在读取';宽度';)

为什么我的按钮没有从&q;1更改为&q;X&q;?

AddEventListner,按键事件不工作

如何根据查询结果重新排列日期

构建器模式与参数对象输入

为什么我不能使用其同级元素调用和更新子元素?

如何使用puppeteer操作所有选项

未找到用于 Select 器的元素:in( puppeteer 师错误)

我想为我的Reaction项目在画布上加载图像/视频,图像正在工作,但视频没有

使用onClick单击子元素时,使用交点观察器的关键帧动画意外运行