next-auth: 登录功能重定向到 /api/auth/error

huangapple go评论63阅读模式
英文:

next-auth: login function redirects to /api/auth/error

问题

我遇到了一个问题,即NextAuth始终返回错误页面

它应该根据我的以下代码返回一个用户:
./app/account/login/page.tsx

"use client";

import React, { useState } from "react";
import { useRouter } from "next/navigation";
import SubmitButton from "@/components/SubmitButton";
import { signIn } from "next-auth/react";

const Login = () => {
  const router = useRouter();
  const [formSubmitting, setFormSubmitting] = useState(false);

  const handleFormSubmit = async (event: any) => {
    setFormSubmitting(true);
    event.preventDefault();
    try {
        const res = await signIn("credentials", {
            email: "john@gmail.com",
            password: "1234",
            redirect: false,
          });
          console.log(res);
    }
    catch(err) {
        console.error(err);
    }
  };

  return (
    <section id="login" className="flex items-center justify-center h-[100vh]">
      <div className="form-wrapper min-w-[300px] rounded-md">
        <h3 className="block mb-6 text-xl font-bold text-gray-900">Login</h3>
        <form onSubmit={handleFormSubmit}>
          <div className="mb-6">
            <label
              htmlFor="email"
              className="block mb-2 text-sm font-medium text-gray-900"
            >
              Your email
            </label>
            <input
              type="email"
              id="email"
              className="bg-gray-50 border border-gray-300 text-gray-900 text-sm rounded-lg focus:ring-blue-500 focus:border-blue-500 block w-full p-2.5"
              placeholder="name@plator.com"
              required
            />
          </div>
          <div className="mb-6">
            <label
              htmlFor="password"
              className="block mb-2 text-sm font-medium text-gray-900"
            >
              Your password
            </label>
            <input
              type="password"
              id="password"
              className="bg-gray-50 border border-gray-300 text-gray-900 text-sm rounded-lg focus:ring-blue-500 focus:border-blue-500 block w-full p-2.5"
              required
            />
          </div>
          <div className="flex items-start mb-6">
            <div className="flex items-center h-5">
              <input
                id="remember"
                type="checkbox"
                value=""
                className="w-4 h-4 border border-gray-300 rounded bg-gray-50 focus:ring-3 focus:ring-blue-300"
              />
            </div>
            <label
              htmlFor="remember"
              className="ml-2 text-sm font-medium text-gray-900"
            >
              Remember me
            </label>
          </div>
          <div className="flex items-start mb-6">
            <a className="text-sm font-medium text-blue-700" href="#">
              Reset my password
            </a>
          </div>
          <div className="flex items-center">
            <SubmitButton
              isSubmitting={formSubmitting}
              onSubmittingLabel={"Logging In"}
              label={"Login"}
            />
          </div>
        </form>
      </div>
    </section>
  );
};

export default Login;

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

import NextAuth, { NextAuthOptions } from "next-auth";
import CredentialsProvider from "next-auth/providers/credentials";

const authOptions: NextAuthOptions = {
  session: {
    strategy: "jwt",
  },
  providers: [
    CredentialsProvider({
      id: "credentials",
      name: "Credentials",
      type: "credentials",
      credentials: {
        username: { type: "text", label: "Username" },
        password: { type: "text", label: "Password" },
      },
      authorize(credentials, req) {
        //我设置它总是返回用户
        return {
          id: "1234",
          name: "John Doe",
          email: "john@gmail.com",
          role: "admin",
        };
      },
    }),
  ],
  pages: {
    signIn: "/account/login",
    error: "/account/login",
  },
  callbacks: {
    async signIn(user) {
      console.log("user: " + user);

      if (!user) return "/account/login?status=fail";

      return "/";
    },
  },
};

export default NextAuth(authOptions);

我已经按照这个链接 https://next-auth.js.org/configuration/providers/credentials 进行了操作,由于我是Next Auth的初学者,我不确定哪里出了问题。

英文:

I'm having a problem where NextAuth always returns to the error page
next-auth: 登录功能重定向到 /api/auth/error

It should return a user as per my code below:
./app/account/login/page.tsx

&quot;use client&quot;;
import React, { useState } from &quot;react&quot;;
import { useRouter } from &quot;next/navigation&quot;;
import SubmitButton from &quot;@/components/SubmitButton&quot;;
import { signIn } from &quot;next-auth/react&quot;;
const Login = () =&gt; {
const router = useRouter();
const [formSubmitting, setFormSubmitting] = useState(false);
const handleFormSubmit = async (event: any) =&gt; {
setFormSubmitting(true);
event.preventDefault();
try {
const res = await signIn(&quot;credentials&quot;, {
email: &quot;john@gmail.com&quot;,
password: &quot;1234&quot;,
redirect: false,
});
console.log(res);
}
catch(err) {
console.error(err);
}
};
return (
&lt;section id=&quot;login&quot; className=&quot;flex items-center justify-center h-[100vh]&quot;&gt;
&lt;div className=&quot;form-wrapper min-w-[300px] rounded-md&quot;&gt;
&lt;h3 className=&quot;block mb-6 text-xl font-bold text-gray-900&quot;&gt;Login&lt;/h3&gt;
&lt;form onSubmit={handleFormSubmit}&gt;
&lt;div className=&quot;mb-6&quot;&gt;
&lt;label
htmlFor=&quot;email&quot;
className=&quot;block mb-2 text-sm font-medium text-gray-900&quot;
&gt;
Your email
&lt;/label&gt;
&lt;input
type=&quot;email&quot;
id=&quot;email&quot;
className=&quot;bg-gray-50 border border-gray-300 text-gray-900 text-sm rounded-lg focus:ring-blue-500 focus:border-blue-500 block w-full p-2.5&quot;
placeholder=&quot;name@plator.com&quot;
required
/&gt;
&lt;/div&gt;
&lt;div className=&quot;mb-6&quot;&gt;
&lt;label
htmlFor=&quot;password&quot;
className=&quot;block mb-2 text-sm font-medium text-gray-900&quot;
&gt;
Your password
&lt;/label&gt;
&lt;input
type=&quot;password&quot;
id=&quot;password&quot;
className=&quot;bg-gray-50 border border-gray-300 text-gray-900 text-sm rounded-lg focus:ring-blue-500 focus:border-blue-500 block w-full p-2.5&quot;
required
/&gt;
&lt;/div&gt;
&lt;div className=&quot;flex items-start mb-6&quot;&gt;
&lt;div className=&quot;flex items-center h-5&quot;&gt;
&lt;input
id=&quot;remember&quot;
type=&quot;checkbox&quot;
value=&quot;&quot;
className=&quot;w-4 h-4 border border-gray-300 rounded bg-gray-50 focus:ring-3 focus:ring-blue-300&quot;
/&gt;
&lt;/div&gt;
&lt;label
htmlFor=&quot;remember&quot;
className=&quot;ml-2 text-sm font-medium text-gray-900&quot;
&gt;
Remember me
&lt;/label&gt;
&lt;/div&gt;
&lt;div className=&quot;flex items-start mb-6&quot;&gt;
&lt;a className=&quot;text-sm font-medium text-blue-700&quot; href=&quot;#&quot;&gt;
Reset my password
&lt;/a&gt;
&lt;/div&gt;
{/* &lt;button
type=&quot;submit&quot;
className=&quot;text-white bg-blue-700 hover:bg-blue-800 focus:ring-4 focus:outline-none focus:ring-blue-300 font-medium rounded-lg text-sm w-full px-5 py-2.5 text-center&quot;
&gt;
Login
&lt;/button&gt; */}
&lt;div className=&quot;flex items-center&quot;&gt;
&lt;SubmitButton
isSubmitting={formSubmitting}
onSubmittingLabel={&quot;Logging In&quot;}
label={&quot;Login&quot;}
/&gt;
&lt;/div&gt;
&lt;/form&gt;
&lt;/div&gt;
&lt;/section&gt;
);
};
export default Login;

and ./app/api/auth/[...nextauth].ts

import NextAuth, { NextAuthOptions } from &quot;next-auth&quot;;
import CredentialsProvider from &quot;next-auth/providers/credentials&quot;;
const authOptions: NextAuthOptions = {
session: {
strategy: &quot;jwt&quot;,
},
providers: [
CredentialsProvider({
id: &quot;credentials&quot;,
name: &quot;Credentials&quot;,
type: &quot;credentials&quot;,
credentials: {
username: { type: &quot;text&quot;, label: &quot;Username&quot; },
password: { type: &quot;text&quot;, label: &quot;Password&quot; },
},
authorize(credentials, req) {
//I&#39;m setting it to always return user
return {
id: &quot;1234&quot;,
name: &quot;John Doe&quot;,
email: &quot;john@gmail.com&quot;,
role: &quot;admin&quot;,
};
},
}),
],
pages: {
signIn: &quot;/account/login&quot;,
error: &quot;/account/login&quot;,
// signOut: &#39;/auth/signout&#39;
},
callbacks: {
async signIn(user) {
console.log(&quot;user: &quot; + user);
if (!user) return &quot;/account/login?status=fail&quot;;
return &quot;/&quot;;
},
},
};
export default NextAuth(authOptions);

I have followed this link https://next-auth.js.org/configuration/providers/credentials , since I am a beginner in Next Auth, I am not sure what is wrong.

答案1

得分: 2

由于您正在使用 Next.js 13 应用程序路由器,您需要按照以下方式配置 NextAuth:

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

import NextAuth from "next-auth"

const handler = NextAuth({
  ...
})

export { handler as GET, handler as POST }

https://next-auth.js.org/configuration/initialization#route-handlers-app

英文:

Since you are using Next.js 13 app router, you need to configure NextAuth as follows:

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

import NextAuth from &quot;next-auth&quot;

const handler = NextAuth({
  ...
})

export { handler as GET, handler as POST }

https://next-auth.js.org/configuration/initialization#route-handlers-app

huangapple
  • 本文由 发表于 2023年6月26日 22:10:14
  • 转载请务必保留本文链接:https://go.coder-hub.com/76557489.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定