下一个验证证明提供商JWT /会话回调

发布于 2025-01-21 09:02:50 字数 2070 浏览 0 评论 0原文

将令牌传递到会话回调时,我遇到了一些困难。我的最终目标是将登录的用户数据发送到客户端。最初,我只是向用户发送电子邮件,但是现在我想将用户的用户名和名称与电子邮件一起发送。通过遵循文档,我们必须通过JWT和会话回调,以使我们开发人员可以访问令牌中的更多数据。当前,在我的JWT回调中,我能够记录用户数据,很棒。但是,当我尝试在会话回调中记录数据时,我会得到一个空{}。任何技巧都非常感谢。先感谢您。

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;
  },
});



I am having some difficulties passing my token to the session callback. My end goal is to send the logged-in users data to the client-side. Originally I was only sending back the users email, but now I would like to have the user's username and name sent along with the email. By following the docs, we have to pass the JWT and Session callback in order for us devs to have access to more data in a token. Currently, in my JWT callback, I am able to log the users data, great. Yet, when I try to log the data in the Session callback, I am getting an empty {}. Any tips are greatly appreciated. Thank you in advance.

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;
  },
});



如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

贪恋 2025-01-28 09:02:50

由于您正在使用:

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

这是下一个实施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 callback中使用:

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)
},

since you are using:

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

that is next-auth v4. in new version of next-auth this code is not valid anymore:

 session: { jwt: true },

Instead, you should use

session: {
    strategy: "jwt",
  },

Then in jwt callback

//   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);
    },

then in session callback:

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)
},
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文