如何解决Next-Auth signIn with Credentials 在 NextJS 中不起作用
我正在将 next-auth 包集成到我的新 nextjs 项目中。 我遵循了所有 nextjs 和 next-auth 文档,但无法找到解决方案。 我面临的问题是这样的: 我想使用提交给我在 Laravel 上运行的 API 服务器的电子邮件和密码登录到我的 NextJS 应用程序。 登录表单的 onSubmit 正在执行以下功能。
import { signIn } from "next-auth/client";
const loginHandler = async (event) => {
event.preventDefault();
const enteredEmail = emailInputRef.current.value;
const enteredPassword = passwordInputRef.current.value;
const result = await signIn("credentials",{
redirect: false,email: enteredEmail,password: enteredPassword,});
console.log("finished signIn call");
console.log(result);
};
下面显示的代码在我的 pages/api/auth/[...nextauth].js
import axios from "axios";
import NextAuth from "next-auth";
import Providers from "next-auth/providers";
export default NextAuth({
session: {
jwt: true,},providers: [
Providers.Credentials({
async authorize(credentials) {
axios
.post("MY_LOGIN_API",{
email: credentials.email,password: credentials.password,})
.then(function (response) {
console.log(response);
return true;
})
.catch(function (error) {
console.log(error);
throw new Error('I will handle this later!');
});
},}),],});
但是当尝试使用正确/不正确的凭据登录时,我在 Google chrome 控制台日志中看到以下显示错误。
POST http://localhost:3000/api/auth/callback/credentials? 401 (Unauthorized)
{error: "CredentialsSignin",status: 401,ok: false,url: null}
我在这里遗漏了什么吗?请帮帮我。
解决方法
来自文档 (https://next-auth.js.org/providers/credentials#example)
async authorize(credentials,req) {
// Add logic here to look up the user from the credentials supplied
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 {
// If you return null or false then the credentials will be rejected
return null
// You can also Reject this callback with an Error or with a URL:
// throw new Error('error message') // Redirect to error page
// throw '/path/to/redirect' // Redirect to a URL
}
}
您当前没有从 null
回调返回用户或 authorize
。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。