在自定义登录页面上抛出错误时下一个身份验证“凭据”重定向

Gur*_*bot 9 oauth reactjs server-side-rendering next.js next-auth

signIn()我有一个自定义登录页面,该页面在提交表单时依次调用该函数。
我只使用“凭据”提供程序。

在服务器端,我只是想抛出一个错误,以便我可以在前端处理它。似乎是一件很容易的事情。

我继续收到一条错误消息:
Error: HTTP GET is not supported for /api/auth/login?callbackUrl=http://localhost:4000/login

我重定向到的网址是:
http://localhost:4000/api/auth/login?callbackUrl=http://localhost:4000/login

这是我的代码: pages/login.js(仅相关代码。其余只是布局。)

<form
    method="post"
    onSubmit={() =>
        signIn("credentials", {
            email: "test",
            password: "test",
        })
    }
>
    <label>
        Username
        <input type="email" />
    </label>
    <label>
        Password
        <input name="password" type="password" />
    </label>
    <button type="submit">Sign In</button>
</form>
Run Code Online (Sandbox Code Playgroud)

页面/api/auth/[...nextauth.js]

import NextAuth from "next-auth";
import Providers from "next-auth/providers";

const options = {
    site: process.env.NEXTAUTH_URL,
    providers: [
        Providers.Credentials({
            id: "chatter",
            name: "Credentials",
            type: "credentials",
            credentials: {
                email: { label: "Email", type: "email", placeholder: "email@domain.com" },
                password: { label: "Password", type: "password" },
            },
            authorize: async credentials => {
                console.log("credentials:", credentials);
                throw new Error("error message"); // Redirect to error page
            },
        }),
    ],
    pages: {
        signIn: "login",
        newUser: null,
    },
};

export default (req, res) => NextAuth(req, res, options);
Run Code Online (Sandbox Code Playgroud)

小智 6

这个答案帮助我解决了我的问题:
https ://stackoverflow.com/a/70760933/11113465

如果设置redirect为 false,该signIn方法将返回以下格式的 Promise:

{
    error: string | undefined // Error code based on the type of error
    status: number // HTTP status code
    ok: boolean // `true` if the signin was successful
    url: string | null // `null` if there was an error
}
Run Code Online (Sandbox Code Playgroud)

然后你可以按照你喜欢的方式处理错误:

    const { error } = await signIn('credentials', {
          phone_number: phoneNumber,
          verification_code: code.toString(),
          redirect: false,
    });

    if (error) {
          // handle error
    } else {
          router.push(callbackUrl);
    }
Run Code Online (Sandbox Code Playgroud)


Mos*_*sen 5

你可以使用这样的东西:

signIn("credentials", {
     redirect: false, 
     email: "test",
     password: "test",
   })
   .then((error) => console.log(error))
   .catch((error) => console.log(error));
Run Code Online (Sandbox Code Playgroud)