reactjs Next-Auth:如何将响应从服务器返回到客户端

k4emjkb1  于 2023-03-12  发布在  React
关注(0)|答案(1)|浏览(96)

我正在使用Next-Auth(使用凭据)进行一个迷你项目,我有以下场景:

const authOptions: NextAuthOptions = {
  providers: [
    CredentialsProvider({
      id: 'credentials',
      name: 'credentials',
      credentials: {},
      async authorize(credentials) {
        const { email, password } = credentials as { email: string; password: string }
        const uuid = uuidv4()
        const res = await fetch("https://myapi.blabla/api/v9/accounts/sign-in/", {
          headers: {
            Authorization: `uuid ${uuid}`,
            "Client-Id": "vrfyrvKmSIRs8s1BZuHcmHNaZuTR2nIF0ZgFt39",
            "Content-Type": "application/json"
          },
          method: "POST",
          body: JSON.stringify({
            email,
            password
          })
        })

        const user = await res.json()

        if (!res.ok) {
          throw new Error(user.message)
        }

        // If no error and we have user data, return it
        if (res.ok && user) {
          return user
        }

        // Return null if user data could not be retrieved
        return null
      }
    })
  ],
  pages: {
    signIn: '/login'
  },
  callbacks: {
    jwt: async ({ token }) => {
      return token
    },
    session({ session, user }) {
      return { ...session, ...user }
    },
  }
}

如果我使用console.log const user = await res.json(),则响应为:

{
   "advertising_id": "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx",
   "api_key": "xxxxxxxxxxxxxxxxxxxxx",
   "username": "xxxxxxx",
   "session": "xxxxxxxxxxxxxxxxxxxxx"
}

问题是,当我在前面使用const session = useSession()时,我只得到:

{
  session: {
    user: {
      name: undefined,
      email: 'micorreo@gmail.com',
      image: undefined,
    },
    expires: '2023-04-09T14:53:56.395Z'
  }
}

我需要的回答应该是这样的:

{
  session: {
    user: {
      name: undefined,
      email: 'micorreo@gmail.com',
      image: undefined,
      session: 'xxxxxxx-xxxxxxxxxxxx',
      advertising_id: 'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx',
      etc...
    },
    expires: '2023-04-09T14:53:56.395Z'
  }
}

我做错了什么吗?我错过了什么吗?或者我需要一个不同的机制来发送会话信息给客户端吗?

jecbmhm3

jecbmhm31#

我看到了一些缺失的东西:

  • 创建CredentialsProvider时,您应该传递
session: {
   strategy: "jwt",
},

secret: process.env.JWT_SECRET,
  • 如果在authorize内部返回user,则该用户将被传递到jwt回调
jwt: async ({ token, user }) => {
  user && (token.user = user);
  return Promise.resolve(token);
},
  • 则此内标识将传递给session回调
session: async ({ session, token }) => {  
    session.user = token.user;
    return Promise.resolve(session);
},

您可以看到example setup

相关问题