You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何解决NextAuth中登录页无法传递手机号的问题?

解决NextAuth中手机号无法传递到后端授权逻辑的问题

核心原因

NextAuth的CredentialsProvider默认不会自动捕获未声明的字段,必须显式定义credentials配置项,框架才会将phone这类自定义参数传递给authorize函数。

修复步骤

1. 在CredentialsProvider中添加credentials配置

修改[...nextauth].js里的CredentialsProvider部分,新增credentials字段声明要接收的参数:

providers: [
  CredentialsProvider({
    name: "Credentials",
    // 显式定义需要接收的参数结构
    credentials: {
      email: { label: "Email", type: "email" },
      phone: { label: "Phone", type: "text" },
      password: { label: "Password", type: "password" }
    },
    authorize: async (credentials) => {
      console.log({ credentials }); // 现在能看到phone字段了

      const { email, phone, password } = credentials;

      try {
        const creds = !!phone
          ? {
              identifier: phone,
              password,
            }
          : {
              identifier: email,
              password,
            };
        console.log("LOGGING IN");
        const { data } = await axios
          .post(API_AUTH, creds, {
            headers: {
              accept: "*/*",
              "Content-Type": "application/json",
            },
          })
          .then((data) => data)
          .catch((err) => console.log({ err }));

        const info = getUser(data?.token);

        const user = {
          name: `${info?.user?.first_name || ""} ${info?.user?.last_name || ""}`,
          email: info?.user?.email || "", // 修复位运算符为逻辑或,避免数值转换错误
          image: info?.user?.image || "",
          sub: "",
          token: data?.token || "",
        };

        if (user) {
          return user;
        }
      } catch (e) {
        const errorMessage = e.response?.data?.message;
        throw new Error(errorMessage);
      }
    },
  }),
]

2. 验证前端参数传递逻辑

确认登录页的signIn调用中,phone字段的赋值逻辑准确:

await signIn("credentials", {
  email: inputType === "email" ? values.username : "",
  phone: inputType === "number" ? values.username : "", // 确保inputType判断正确,values.username为有效手机号
  password: values.password,
  callbackUrl: "/dashboard",
})

3. 调试确认参数接收

在authorize函数开头打印credentials,检查phone字段是否已被正确传递。如果仍未收到,排查前端inputType的触发逻辑,比如用户选择手机号登录时,inputType是否确实为"number"。

额外注意事项

  • 原代码中email: info?.user?.email | ""使用了位运算符,需改为逻辑或||,否则会引发非预期的数值转换错误。
  • 确保后端API能正确处理identifier为手机号的请求。

内容的提问来源于stack exchange,提问作者Youzef

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.12 16:05:01