Automatically refresh token via timeout #205
matt-clegg
started this conversation in
Ideas
Replies: 1 comment
-
I've written an auth refresh client side plugin which seems to achieve what I'm after.
Here's the source code if anyone would like to try it out or has any suggestions: export default defineNuxtPlugin(async () => {
const { expires, refreshTokens, refreshToken } = useDirectusToken();
const user = useDirectusUser();
watch(user, async (val, oldVal) => {
if (!oldVal && val) {
// User has logged in, begin auto refresh
await checkRefresh();
}
});
let windowTimeout: number | null = null;
async function checkRefresh () {
if (isNaN(expires.value)) {
return;
}
const expiresInMs = expires.value - Date.now();
// Add a small buffer window to the expire time when refreshing tokens
const expiresBufferMs = 10_000; // 10 seconds
if (isNaN(expiresInMs)) {
return;
}
if (!refreshToken.value) {
return;
}
if (expiresInMs > expiresBufferMs) {
// The token will expire some time after the buffer window
const timeout = expiresInMs - expiresBufferMs;
if (timeout > 1) {
if (windowTimeout) {
window.clearTimeout(windowTimeout);
}
windowTimeout = window.setTimeout(async () => {
if (!user.value) {
// The user has logged out so we won't perform the auto refresh or queue another timeout
return;
}
await refreshTokens();
await checkRefresh();
}, timeout);
} else {
throw new Error(`Expires timeout was less than 1: '${timeout}'`);
}
} else {
// The token has already expired, or we are in the buffer window
await refreshTokens();
await checkRefresh();
}
}
await checkRefresh();
}); |
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
I've noticed that the auth token will expire if the user idles on the same page for some time.
This can be an issue if the user can interact with the Directus backend through a Nuxt page, for example the user could create or update an item in a collection that requires the user to be logged in.
Could the module be extended with a plugin that automatically calls
refreshTokens()
, probably with a timeout based on theexpires
value from theuseDirectusToken()
composable?Admittedly my
ACCESS_TOKEN_TLL
is set to the default of 15 minutes, but it means the user will be considered logged out if they interact with the page after being idle for over 15 minutes.Beta Was this translation helpful? Give feedback.
All reactions