[英]failed login redirects me to /api/auth/error on next-auth
[英]Return error information from API when using Next-auth
是否可以允许 next-auth 从 API 返回错误并从客户端传递它们?
例如,如果用户的 email 或密码不正确,则会返回 API。 在我们的移动应用程序上,这很好用。 虽然在网站上,我们使用的是 Next-auth。 使用文档中的凭证示例,最好将返回值更改为 object。
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 }
}
}
})
]
请让我知道是否还有其他与此相关的帖子,因为我无法在网上找到它。
是的,这应该允许您这样做,尽管在凭证中,当将值传递给下一个身份验证时,添加一个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 }))
}
}
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.