在 Next-auth 中将更多数据传递给会话

A.A*_*kov 8 next.js next-auth

我们正在我们的网站上进行 OTP 身份验证。因此,为了获得授权,访问者在输入中输入他的电话号码,我们向他发送一个 OPT 号码,他再次输入发送的选项,然后如果匹配,我们向他发送他的帐户凭据(令牌、用户 ID)(如果存在),或者我们创建新的,我们希望使用 next-auth 在会话中保存该凭证。

这是我到目前为止所得到的:

export default NextAuth({
  providers: [
    CredentialsProvider({
      credentials: {
        phoneNumber: { label: 'PhoneNumber', type: 'text' },
        code: { label: 'Code', type: 'text' },
        type: { label: 'Type', type: 'text' },
      },
      async authorize(credentials, req) {
        const user_needs = await requests.auth.signInEnterOtp(
          credentials.phoneNumber,
          credentials.code,
          credentials.type
        )
        return user_needs.ok ? true : null
      },
    }),
  ],
  callbacks: {
    async session({ session, user, token }) {
      return session
    },
  },
  secret: process.env.JWT_SECRET,
})
Run Code Online (Sandbox Code Playgroud)

我需要保存user_needs会话中的内容,但如何将其传递authorizesession

我尝试返回user_needinauthorize但它没有传递给session回调。

A.A*_*kov 21

最终我想出了这样的方法:

async authorize(credentials, req) {
 const res = fetchUserInfo(credentials.opt)
 if(res.ok) return {user: res.data} // res.data contains whatever received from DB call => fetchUserInfo(credentials.opt)

 return null
},
callbacks: {

 async jwt({ token, user }) {
  // the user present here gets the same data as received from DB call  made above -> fetchUserInfo(credentials.opt)

  return { ...token, ...user }
 },
  async session({ session, user, token }) {
  // user param present in the session(function) does not recive all the data from DB call -> fetchUserInfo(credentials.opt)

  return token
 },
},
Run Code Online (Sandbox Code Playgroud)

编辑:2023 年 2 月 15 日

我自己现在更好地理解了回调周期:

authorize --> jwt --> session
Run Code Online (Sandbox Code Playgroud)

jwtcallback(cb) 接受cb 返回user的对象authorize

默认情况下jwt返回token,然后从那里返回的东西可以在cbtoken的对象中使用session

例子:

authorize --> jwt --> session
Run Code Online (Sandbox Code Playgroud)

但是当我使用时Providers,我不会有authorizecb,所以为了获取用户的角色,我需要在 cb 中查询 db,jwt但是这个回调运行了很多,我不知道什么是更好的选择