next.js 为什么在下一次验证回调中未定义用户和帐户对象

uyhoqukh  于 2023-05-06  发布在  其他
关注(0)|答案(1)|浏览(117)

我试图控制台日志session.user.accessToken和clientsecret,结果是未定义的,所以我前往NextAuth.js查看是否有问题,似乎account和user在jwt回调函数中未定义
console.log(account)是未定义的,我错了吗?
这是我的[...Nextauth].js文件

export default NextAuth({
  // Configure one or more authentication providers
  providers: [
    SpotifyProvider({
      clientId: process.env.NEXT_PUBLIC_CLIENT_ID,
      clientSecret: process.env.NEXT_PUBLIC_CLIENT_SECRET,
      authorization: LOGIN_URL
    })
    // ...add more providers here
  ],

  secret: process.env.JWT_SECRET,
  pages: {
    login: "/login"
  },
  callbacks: {
    async jwt({ token, account, user, profile }) {
      //initial user sign in

      if (account && user) {
        console.log({ token, user, account, profile });
        return {
          ...token,
          accessToken: account.access_Token,
          refreshToken: account.refresh_token,
          username: account.providerAccountId,
          accessTokenExpires: account.expires_at * 1000 //handle expiry time in ms
        };
      }
      //return the previous token if current token is expired

      if (Date.now() < token.accessTokenExpires) {
        console.log("Existing token is valid");
        return token;
      }

      //refresh token
      console.log("Existing token has expired");
      return await refreshAccessToken(token);
    },

    async session({ session, token }) {
      session.user.accessToken = token.accessToken;
      session.user.refreshToken = token.refreshToken;
      session.user.username = token.username;
      return session;
    }
  }
});
62o28rlo

62o28rlo1#

您可以在控制台中进一步检查。例如,在[...nextauth].js中添加如下内容:

events: {
    signIn(message) {
      console.log('signin message', message)
    },
    session(){...},
    signOut(message) {
      console.log(message)
    },
  },

  // Enable debug messages in the console if you are having problems
  debug: true,

参考:https://next-auth.js.org/configuration/events

相关问题