Next Auth Credentials Provider JWT / Session 回调

Next Auth Credentials Provider JWT / Session callback

我在将令牌传递给会话回调时遇到了一些困难。我的最终目标是将登录用户数据发送到客户端。最初我只是发回用户的电子邮件,但现在我想将用户的用户名和姓名与电子邮件一起发送。按照文档,我们必须传递 JWT 和会话回调,以便我们的开发人员能够访问令牌中的更多数据。目前,在我的 JWT 回调中,我能够记录用户数据,太棒了。然而,当我尝试在 Session 回调中记录数据时,我得到一个空的 {}。非常感谢任何提示。提前谢谢你。

import NextAuth from "next-auth/next";
import CredentialsProvider from "next-auth/providers/credentials";

// Helper Functions
import {
  connectToDatabase,
  comparePasswords,
} from "../../helper/HelperFunctions";

export default NextAuth({
  session: { jwt: true },
  providers: [
    CredentialsProvider({
      async authorize(credentials) {
        const client = await connectToDatabase();

        const userCollection = client.db().collection("users");

        const user = await userCollection.findOne({
          email: credentials.email,
        });

        // const userInfo = {
        //   firstName: user.firstName,
        //   lastName: user.lastName,
        //   email: user.email,
        //   userName: user.userName,
        // };

        // console.log(userInfo);

        if (!user) {
          client.close();

          throw new Error("No user found!");
        }

        const isValid = await comparePasswords(
          credentials.password,
          user.password
        );

        if (!isValid) {
          client.close();

          throw new Error("Invalid password");
        }

        client.close();

        if (user) {
          return {
            user,
          };
        } else {
          return null;
        }
      },
    }),
  ],
  callbacks: {
    async jwt({ token, user }) {
      // Persist the OAuth access_token to the token right after signin
      if (user) {
        token = user;
        console.log(token);
        // all of the user data is being logged, yet how to pass it down to session callback so i can use all the user data in the client?
      }
      return token;
    },
  },
  async session({ session, token, user }) {
    session.user = token;
    console.log(session.user);
    // nothing gets logged into the terminal?? WTF

    return session;
  },
});



因为您正在使用:

import CredentialsProvider from "next-auth/providers/credentials";

即 next-auth v4。在 next-auth 的新版本中,此代码不再有效:

 session: { jwt: true },

相反,您应该使用

session: {
    strategy: "jwt",
  },

然后在jwt回调

//   jwt callback is only called when token is created
async jwt({ token, user }) {
      if (user) {
        token = user;
        // token = user;
        token.user=user
      }
      return Promise.resolve(token);
    },

然后在 session 回调中:

session: async ({ session, token }) => {
  // session callback is called whenever a session for that particular user is checked
 // in above function we created token.user=user
  session.user = token.user;
  // you might return this in new version
  return Promise.resolve(session)
},