我在我的下一个项目中使用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
.任何帮助都将不胜感激.