NextAuth:如何在不重定向的情况下返回自定义错误

9nvpjoqh  于 2023-08-04  发布在  其他
关注(0)|答案(2)|浏览(102)

我一直在考虑使用用户名和密码凭据实现NextAuth,但我没有找到向客户端返回自定义错误的方法。看起来我只能从authorize方法返回一个200ok或者重定向到一个错误页面,然后你可以在查询字符串中添加一个自定义错误。然而,这不是一个适当的解决方案,我的情况下,我需要客户端只是接收一个自定义的错误代码或消息从sigIn调用。
如何返回自定义错误(如
“无效的电子邮件地址”
“帐户被阻止”
“密码无效”
或任何其他定制要求?
谢啦,谢啦

ccrfmcuu

ccrfmcuu1#

如果你不使用next-auth页面,而是使用自定义页面,那么在使用signIn函数时,你必须在登录页面中将redirect设置为false,下面是一个例子:

// login.jsx

const [datas, setDatas] = useState({ credential: '', password: '' })

const handleSubmit = async e => {
    e.preventDefault()
    try {
      // siging in
      const res = await signIn('credentials', {
        credential: datas.credential, // can be changed to `email` or `username` or anything else
        password: datas.password,
        redirect: false // this is important
      })
      if (res?.status == 200) {
        push('/')
      } else {
        throw new Error(res?.error)
      }
    } catch (error) {
      console.log(error.message) // error in the provider
    }
}

字符串
而在提供程序中,你必须抛出你希望被看到的错误

// [...nextauth].js

providers: [
    // credentials provider
    CredentialsProvider({
        type: 'credentials',
        credentials: {},

        // authorization function
        async authorize(credentials, req) {
            const { credential, password } = credentials

            // admin profile
            let data = { credential : 'test', password: 'abcd' } // replace this

            if (!data) throw new Error('no user found')
            if (data.credential != credential) throw new Error('invalid credentials')

            // comparing the password
            const compared = data.password != password // replace this

            // checking if the password was correct
            if (!compared) throw new Error('invalid credentials')

            return data // success
        }
    })
],


如果我打错字的话要小心

lc8prwob

lc8prwob2#

我通过实现一个signIn回调找到了所需的解决方案。authorize方法可以返回一个自定义对象,signIn回调函数捕获它并相应地处理它。
请参阅此处的文档

// [...nextauth].js
providers: [
// credentials provider
CredentialsProvider({
    type: 'credentials',
    credentials: {},

    // authorization function
    async authorize(credentials, req) {
        const { credential, password } = credentials

        if (myCustomCondition) {
          return { error: 'my custom error' };
        }
        return data // success
    }
 })
],
callbacks: {
   async signIn({ user, account, profile, email, credentials }) {
      if(user?.error === 'my custom error') {
         throw new Error('custom error to the client')
      }
   }
}

字符串
在客户端,我们可以评估错误消息并采取相应的措施:

const res = await signIn('credentials', {
    credential: data.credential,
    password: data.password,
    redirect: false
  })
  if (res?.status == 200) {
    push('/')
  } else if(res?.error === 'custom error to the client') {
    // handle this particular error
  } else {
    // handle generic error
  }

相关问题