如何解决Next-Auth 凭据提供程序和 MongoDB
我在使用 Next-Auth 中的凭据提供程序实现身份验证时遇到问题
由于某种原因,认证失败并且永远不会返回用户对象
import Providers from "next-auth/providers";
import dbConnect from "../../../utils/dbConnect";
const options = {
NEXTAUTH_URL: process.env.NEXTAUTH_URL,providers: [
Providers.Credentials({
// The name to display on the sign in form (e.g. 'Sign in with...')
name: "Eveira Account",id: "eveira-login",// The credentials is used to generate a suitable form on the sign in page.
// You can specify whatever fields you are expecting to be submitted.
// e.g. domain,username,password,2FA token,etc.
credentials: {
email: { label: "Email",type: "email" },password: { label: "Password",type: "password" },},authorize: async (credentials) => {
// Add logic here to look up the user from the credentials supplied
// const user = {id: 1,name: 'J Smith',email: 'jsmith@example.com'}
const dbConnection = await dbConnect();
const user = await dbConnection.models.User.findOne({
emailAddress: credentials.email,});
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:
// return Promise.reject(new Error('error message')) // Redirect to error page
// return Promise.reject('/path/to/redirect') // Redirect to a URL
}
},}),],session: {
jwt: true,maxAge: 30 * 24 * 60 * 60,// A database is optional,but required to persist accounts in a database
database: process.env.DATABASE_URL,};
export default (req,res) => NextAuth(req,res,options);
我怀疑查询失败,因为没有处理 console.log 以及验证失败的原因
import mongoose from "mongoose";
const connection = { isConnected: false }; /* creating connection object*/
let uri = process.env.DATABASE_URL;
if (!uri) {
throw new Error(
"Please define the MONGODB_URI environment variable inside .env.local"
);
}
export default async function dbConnect() {
let db;
if (!connection.isConnected) {
db = await mongoose.connect(uri,{
useNewUrlParser: true,useCreateIndex: true,useFindAndModify: false,useUnifiedTopology: true,});
connection.isConnected = db.connections[0].readyState;
console.log("-----db isConnected-----",models);
}
return db; // IMPORTANT! -- return an instance of the db
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。