自定义错误"/>
NextAuth:如何在不重定向的情况下返回自定义错误
我一直在考虑使用用户名和密码凭据实现 NextAuth,但没有找到将自定义错误返回到客户端的方法。看来我只能从授权方法返回 200 ok 或重定向到错误页面,然后您可以在查询字符串中添加自定义错误。然而,这对于我的情况来说不是一个正确的解决方案,因为我需要客户端仅从 sigIn 调用接收自定义错误代码或消息。
如何返回自定义错误,例如
“电子邮件地址无效”
“帐户被封锁”
“密码无效”
或者需要任何其他定制吗?
谢谢
回答如下:如果您的应用程序没有使用 next-auth 页面并使用自定义页面,则在使用
signIn
功能时,必须在登录页面中将重定向设置为 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
}
})
],
如果我有错别字,请小心
更多推荐
NextAuth:如何在不重定向的情况下返回自定义错误
发布评论