使用来自 next-auth 的凭据提供程序为我们的用户提供简单的电子邮件/密码登录流程,我正在尝试找出会话选项的最佳组合来处理刷新令牌。
目前,成功登录后,我们的 API 会发回 JWT 和USER_SESSION_LENGTH
30 分钟的配置属性。
我已经为clientMaxAge
and设置了 30 分钟的提供程序选项组合keepAlive
,并且在 JWT 回调中,检查到期时间是否小于“almostNow”Date.now()
调用,如果是,则重新获取新的 JWT 并重置到期。
虽然这似乎有效,但我认为我没有clientMaxAge/keepAlive
正确使用。我应该如何正确设置/配置这些值以协同工作?
// _app.tsx
const sessionOptions = {
clientMaxAge: 60 * 30, // Re-fetch session if cache is older than 30 minutes
keepAlive: 60 * 30
};
<Provider options={sessionOptions} session={pageProps.session}>
<Component {...pageProps} />
</Provider>
// [...nextauth].ts
const callbacks: CallbacksOptions = {
async jwt(token: any, user: any) {
if (user) {
token.accessToken = user.token;
token.expires = Date.now() + user.config.USER_SESSION_LENGTH * 1000;
}
if (token?.accessToken) {
const tokenExpiry = token.expires;
const almostNow = Date.now() + 60 * 1000; // random check of a minute past now so it won't run the first time, but on the refetch after 30 minutes.
if (tokenExpiry !== undefined && tokenExpiry < almostNow) {
try {
const newToken = await api.renewToken(token.accessToken); // hit our backend for new token
token.accessToken = newToken.token;
token.expires = Date.now() + user.config.USER_SESSION_LENGTH * 1000;
} catch (error) {
console.error(error, 'Error refreshing access token');
}
}
}
return token;
},
}