使用Next-auth时返回API错误信息

kxxlusnw  于 2023-06-29  发布在  其他
关注(0)|答案(2)|浏览(166)

是否可以允许next-auth从API返回错误并从客户端传递它们?
例如,如果用户的电子邮件或密码不正确,则API将专门返回。在我们的移动的应用程序上,这很有效。虽然在网站上,我们使用Next-auth。使用文档中的凭据示例,将返回值更改为对象将是非常好的。

import CredentialsProvider from "next-auth/providers/credentials"
providers: [
  CredentialsProvider({
    name: "Credentials",
 
    credentials: {
      username: { label: "Username", type: "text", placeholder: "jsmith" },
      password: {  label: "Password", type: "password" }
    },
    async authorize(credentials, req) {
      const user = { id: 1, name: "J Smith", email: "jsmith@example.com" }

      if (user) {
        // Any object returned will be saved in `user` property of the JWT
        return user
      } else {
        // Return an object that will pass error information through to the client-side.
        return { errors: user.errors, status: false }
      }
    }
  })
]

请让我知道,如果有另一个职位,涉及到这一个,因为我无法在网上找到它。

nbysray5

nbysray51#

是的,这应该允许您这样做,尽管在凭证中,当将值传递给下一个auth时,添加redirect:false
您可以在此处找到文档
因此,您的登录方法将如下所示。

signIn('credentials', { redirect: false, username:'username', password: 'password' })

您的代码可以如下所示

import CredentialsProvider from "next-auth/providers/credentials"
providers: [
  CredentialsProvider({
    name: "Credentials",
 
    credentials: {
      username: { label: "Username", type: "text", placeholder: "jsmith" },
      password: {  label: "Password", type: "password" }
    },
    async authorize(credentials, req) {
      const user = { id: 1, name: "J Smith", email: "jsmith@example.com" }

      if (user) {
        // Any object returned will be saved in `user` property of the JWT
        return user
      } else {
        // Return an object that will pass error information through to the client-side.
        throw new Error( JSON.stringify({ errors: user.errors, status: false }))
      }
    }
  })
hc2pp10m

hc2pp10m2#

我通过在authorize函数中使用带有catch语句的promise来返回正确的错误信息:

export const authOptions: NextAuthOptions = {
  session: {
    strategy: "jwt",
  },
  secret: process.env.NEXTAUTH_SECRET,
  providers: [
    CredentialsProvider({
      name: "credentials",
      credentials: {
        email: {
          label: "Email",
          type: "email",
          placeholder: "example@example.com",
        },
        password: { label: "Password", type: "password" },
      },
      async authorize(credentials: any) {
        // console.log(credentials);
        const { user, jwt } = await axios
          .post(`http://localhost:1337/api/auth/local`, {
            identifier: credentials.email,
            password: credentials.password,
          })
          .then(({ data }) => {
            return data;
          })
          .catch((error) => {
            throw new Error(JSON.stringify(error.response.data));
          });

        return { jwt, ...user };
      },
    }),
  ],
};
const handler = NextAuth(authOptions);
export { handler as GET, handler as POST };

next-auth错误的类型是string,因此您需要将其字符串化为JSON,然后从客户端将其转换回对象。

相关问题