如何在 Next-Auth v5.0.0-beta.5 中使用凭据时返回自定义错误

问题描述 投票:0回答:1

请问我目前正在使用 [电子邮件受保护] 来处理我的 nextJs 应用程序中的用户身份验证。我希望能够在使用凭据时用户身份验证失败时向客户端发送自定义错误。

我尝试过这样做,它可以在版本 4 中工作:

     async authorize(credentials: any) {
                let urlencoded = new URLSearchParams();

                urlencoded.append('email', credentials.email);
                urlencoded.append('password', credentials.password);
                const res = await AuthApiInstance.signIn<UserSchemaType>(urlencoded);

                console.log(res);

                if (res.isError && !res.resData) {
                    throw new Error(JSON.stringify({ errors: res.error, status: res.statusCode }))
                };

                if (res.resData?.data.token) {
                    encryptCookieDataAction(res.resData?.data.token, EncryptionCookiesKeys.AdminToken)
                }

                return res.resData?.data as any
            },

但它不再起作用了。

如果有人可以帮助我如何在使用凭据时将自定义错误发送回客户端,我将非常感激。

reactjs next.js next-auth app-router
1个回答
0
投票

我遇到了一个问题,即版本

5.0.0-beta.16
的登录表单中的登录无法按预期工作。为了实现自定义用户登录体验,我实现了服务器操作函数作为替代方法。此功能取代了在登录表单中直接使用signIn。

"use server"

import { DEFAULT_LOGIN_REDIRECT } from "@/routes"
import { AuthError } from "next-auth"

import { signIn } from "@/lib/auth"

export const login = async (phone: string, code: string, callbackUrl?: string | null) => {
  try {
    await signIn("phone", { phone, code, redirectTo: callbackUrl || DEFAULT_LOGIN_REDIRECT })
  } catch (error) {
    console.error("phone login: ", error)
    if (error instanceof AuthError) {
      return { error: "error", message: error.message, status: 401 }
    }

    throw error
  }
}
© www.soinside.com 2019 - 2024. All rights reserved.