gpt4 book ai didi

javascript - Next-Auth 使用凭据登录在 NextJS 中不起作用

转载 作者:行者123 更新时间:2023-12-04 17:17:47 24 4
gpt4 key购买 nike

我正在将 next-auth 包集成到我的新 Next.js 项目中。我已关注所有 Next.js 和 next-auth 文档,但找不到解决方案。
我面临的问题是这样的:
我想使用提交到我在 Laravel 上运行的 API 服务器的电子邮件和密码登录到我的 Next.js 应用程序。
提交登录表单时,我正在执行以下功能。

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打回来。

关于javascript - Next-Auth 使用凭据登录在 NextJS 中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68142134/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com