为啥在页面转换时不调用 next-auth jwt 回调?

Posted

技术标签:

【中文标题】为啥在页面转换时不调用 next-auth jwt 回调?【英文标题】:why doesn't next-auth jwt callback get called on page transitions?为什么在页面转换时不调用 next-auth jwt 回调? 【发布时间】:2021-08-18 15:10:56 【问题描述】:

我正在使用 next-auth Credentials 提供程序在我的下一个带有自定义 django 后端的 js 应用程序中实现身份验证。

这是我的 jwt 回调:

async jwt(token, user, account) 
    if (user && account) 
      // The user has just logged in.
      const decoded = jwt_decode(user.access)
      token.accessToken = user.access
      token.refreshToken = user.refresh
      token.accessTokenExpires = decoded.exp
      return token
    
    if ((Date.now() + 15 * 1000) <= (token.accessTokenExpires * 1000)) 
      // The user has logged in before but the token.accessToken has not been expired.
      return token
    
    // token.accessToken is expired and we need to get a new jwt using token.refreshToken.
    const newJwt = await refreshJwt(token.refreshToken)
    if (newJwt) 
      token.accessToken = newJwt
      const decoded = jwt_decode(newJwt)
      token.accessTokenExpires = decoded.exp
      return token
    
    // token.accessToken and token.refreshToken are both expired.
    return 

这就是问题所在:

jwt(token.accessToken) 过期后,jwt callback 将不会被调用。所以它无法刷新 jwt(token.accessToken)。

但是当我手动刷新页面(硬刷新)时,它会被调用并使用 token.refreshToken 正确设置新的 jwt(token.accessToken)。

当用户在他/她的浏览器上更改标签时,它也会被调用并正确设置新的 jwt。

我希望每次使用钩子 useSession 时都能调用 jwt callback。 (我在所有页面中都使用useSession,包括服务器端呈现的页面和静态生成的页面)。

【问题讨论】:

你有完整的供应商代码吗?如果您可以分享它以帮助其他开发人员,可能会非常有用。 【参考方案1】:

我通过在_app.js 中将选项传递给next-auth/clientProvider 解决了这个问题:

return (
    <Provider session=session
              options=clientMaxAge: TIME_INTERVAL_IN_SECONDS_WHICH_HAS_TO_BE_LESS_THAN_JWT_EXPIRATION_TIME >
        ...
    </Provider>
)

对于v4,选项被refetchInterval替换,所以应该如下:

return (
    <SessionProvider session=session refetchInterval=TIME_INTERVAL_IN_SECONDS_WHICH_HAS_TO_BE_LESS_THAN_JWT_EXPIRATION_TIME>
        <Component ...pageProps />
    </SessionProvider>
)

【讨论】:

以上是关于为啥在页面转换时不调用 next-auth jwt 回调?的主要内容,如果未能解决你的问题,请参考以下文章

为啥在组件加载时不调用 useEffect(()=...,[]) ?

在 next-auth 中制作自定义电子邮件登录页面时找不到“next-auth/react”模块

如何在 Next.js 中使用 next-auth 实现凭据授权?

为啥numpy数组的astype方法在转换类型时不修改输入?

为啥这个 constexpr 静态成员函数在调用时不被视为 constexpr?

为啥在asp.net中使用自定义404页面时不存在的页面返回302状态