You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何解决Next-Auth中Google登录生产环境的JWT过期问题?

Next-Auth Google登录生产环境出现JWT过期错误(本地正常)

本地环境用Next-Auth实现Google登录功能完全正常,但生产环境中选择Google账号后触发OAUTH_CALLBACK_ERROR,具体错误为JWT过期,错误日志如下:

[next-auth][error][OAUTH_CALLBACK_ERROR] 
https://next-auth.js.org/errors#oauth_callback_error JWT expired, now 1679915090, exp 1679893540 {
error: RPError: JWT expired, now 1679915090, exp 1679893540
       at Client.validateJWT (/app/node_modules/openid-client/lib/client.js:956:15)
       at Client.validateIdToken (/app/node_modules/openid-client/lib/client.js:745:60)
       at Client.callback (/app/node_modules/openid-client/lib/client.js:488:18)
       at runMicrotasks (<anonymous>)
       at processTicksAndRejections (node:internal/process/task_queues:96:5)
       at async oAuthCallback (/app/node_modules/next-auth/core/lib/oauth/callback.js:109:16)
       at async Object.callback (/app/node_modules/next-auth/core/routes/callback.js:52:11)
       at async AuthHandler (/app/node_modules/next-auth/core/index.js:201:28)
       at async NextAuthHandler (/app/node_modules/next-auth/next/index.js:24:19)
       at async /app/node_modules/next-auth/next/index.js:60:32 {
     name: 'OAuthCallbackError',
     code: undefined
   },
   providerId: 'google',
   message: 'JWT expired, now 1679915090, exp 1679893540'
 }

当前Next-Auth配置代码:

export default NextAuth({
    providers: [
        GoogleProvider({
            clientId: process.env.GOOGLE_CLIENT_ID,
            clientSecret: process.env.GOOGLE_CLIENT_SECRET
        })
    ],
    secret: process.env.SECRET,
    callbackUrl: process.env.CALLBACK_URL,
    debug: false,
    jwt: {
        maxAge: 3 * 24 * 60 * 60,
    },
})

解决方法

  • 修正生产服务器系统时间:从错误日志的时间戳可以看出,服务器当前时间(1679915090)比JWT过期时间(1679893540)快了近6小时。Google返回的id_token有效期很短,服务器时间不准会直接判定token过期。将服务器时间同步到NTP服务器,确保和实际时间一致。
  • 核对callbackUrl配置:生产环境的CALLBACK_URL必须和Google Cloud Console中配置的授权回调地址完全匹配,包括协议(http/https)、域名、路径,任何细节不匹配都可能导致授权流程延迟,间接引发token过期。
  • 临时添加时间容错(不推荐长期使用):如果服务器时间暂时无法修正,可以在Next-Auth的jwt配置中添加clockTolerance参数,允许一定的时间误差:
    jwt: {
        maxAge: 3 * 24 * 60 * 60,
        clockTolerance: 600 // 允许10分钟的时间误差
    },
    
  • 排查生产环境网络延迟:如果服务器到Google OAuth服务器的网络延迟过高,token可能在传输过程中就已过期。测试服务器到accounts.google.com的连通性和延迟,必要时更换服务器区域或优化网络。

内容的提问来源于stack exchange,提问作者nendi isharmawan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.26 20:10:35