mongodb 如何在NextAuth中使用session返回Mongo的_id?

eqqqjvef  于 2023-11-17  发布在  Go
关注(0)|答案(1)|浏览(150)

我是NextAuth的新手。我正在使用Mongodb的NextAuth凭据提供程序。根据NextAuth文档,如果我想检查用户会话,我可以在客户端组件中使用useSession(),而在服务器组件中使用getServerSession()。默认情况下,会话包含一个用户对象,该对象仅包含名称,电子邮件,但是,如果我想向我的会话传递额外的属性,比如Mongodb在创建文档时生成的_id,该怎么办呢?
根据NextAuth,如果我想向会话传递额外的数据,我应该在我的auth选项中添加一个acync回调会话。由于我使用的是JWT策略(默认策略),我应该在会话回调之前添加一个acync jwt回调。
我的授权选项:

export const authOptions = {
    providers: [
        CredentialsProvider({
            name: 'Sign in',
            credentials: {},
            async authorize(credentials, req) {
                const { email, password } = credentials

                try {
                    await connectDB()
                    const customer = await Customer.findOne({ email })
                    if (!customer) null

                    //check whether the passwords are correct
                    const pwdComparisonResult = await bcrypt.compare(password, customer.password)
                    if (pwdComparisonResult) {
                        return customer
                    }

                    return null

                } catch (error) {
                    console.log('error ', error);
                }
            }
        }),
    ],
    callbacks: {
        async jwt(token, user, session) {
            //What I should write and return inside jwt?
        },

        async session({ session, token, user }) {
            //What I should write and return inside session?
        }
    },
    session: {
        strategy: "jwt"
    },
    pages: {
        signIn: '/login',
    }
}

字符串
据我所知,jwt将返回一个token,session回调将接收这个token并返回一个session。这是真的吗?谁能解释一下数据如何在authorize、jwt和session之间流动,以及我应该在jwt和session回调中编写什么逻辑,以便能够访问mongo id沿着name和email属性?

unftdfkk

unftdfkk1#

authorize回调函数接收credentialsreq参数。credentials参数包含身份验证过程中获得的信息。

// Callbacks are asynchronous functions you can use to control what happens when an action is performed.
  callbacks: {
    //   jwt callback is only called when token is created
    jwt: async ({ token, user }) => {
      // user is obj that we have received from authorize. in your case it is customer
      user && (token.user = user);
      // it should be Promise.resolve(token) otherwise you may get some error
      return Promise.resolve(token);
    },
    session: async ({ session, token }) => {
      // session callback is called whenever a session for that particular user is checked
      //   console.log("user in ...next auth api", token);
      // we can add more properties here to the session obj
      session.user = token.user;
      console.log("session", session);
      // since I get error, I return Promise.resolve(session)
      return Promise.resolve(session);
    },

字符串

相关问题