NEXT Auth v5 服务器端会话更新

问题描述 投票:0回答:1

我正在尝试使用 JWT 策略通过

NextAuth.js v5
更新用户会话。

我的最终目标是切换到服务器端的另一家活跃公司。当我使用他们的

unstable_update
函数时,它实际上触发了我的 JWT 回调。

    async jwt({ token, user, trigger, session }) {
      if (user) {
        const userId = token.sub as string;
        const user = await prisma.user.findUnique({
          where: { id: +userId },
        });
        token.role = user?.role as Role;
        token.username = user?.username as string;
        token.firstName = user?.firstName as string;
        token.lastName = user?.lastName as string;
        token.activeCompanyId = user?.activeCompanyId;
      }
      if (trigger === 'update') {
        console.log('Update triggered, session:');
        console.log(session);
        token.activeCompanyId = session.user.activeCompanyId;
      }
      return token;
    },
    async session({ token, session }: { token: JWT; session: Session }) {
      console.log('Token in session callback');
      console.log(token);
      const userId = token.sub as string;
      session.user.userId = +userId;
      session.user.role = token.role as Role;
      session.user.firstName = token.firstName;
      session.user.lastName = token.lastName;
      session.user.username = token.username;
      session.user.activeCompanyId = token.activeCompanyId;
      return session;
    },
  }

触发后,我的会话被更新,但随着会话的其他调用,它被取消,

session.user.activeCompanyId
中的最终结果是
null
。 我做对了吗?

javascript session next.js oauth jwt
1个回答
0
投票

正如文档所说:

The arguments user, account, profile and isNewUser are only passed the first time this callback is called on a new session, after the user signs in. In subsequent calls, only token will be available.

因此,您应该仅在

token.activeCompanyId
时分配
session != null

我希望在

session
回调中收到的
session
参数仍然具有
user.activeCompanyId
值,所以我认为您根本不需要从
token
解析它。

© www.soinside.com 2019 - 2024. All rights reserved.