I am currently working on an expressjs application which manages the session for a bunch of micro services. I want to run middleware on all requests that will handle any necessary refresh_token logic before the request is then passed on to the micro service.
The issue I have is that when the requests happen in parallel they all attempt to handle the refresh_token, which causes some of the requests to blow-up.
I realise I can handle the logic in the clientside application through an axios interceptor or similar, but the api is used by multiple clients so I would prefer to handle centrally.
Currently my thoughts are something like this:
const refreshTokenPromise = {};
function enqueueRefreshToken(refreshToken) {
if (refreshTokenPromise[refreshToken]) {
refreshTokenPromise[refreshToken].listeners = refreshTokenPromise[refreshToken].listeners + 1;
} else {
refreshTokenPromise[refreshToken] = {
promise: axios({
method: 'post',
url: `${authServiceHostname}/oauth/token?grant_type=refresh_token&refresh_token=${refreshToken}`,
timeout: 30000,
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
},
body: {}
}),
listeners: 1
};
}
return refreshTokenPromise[refreshToken];
}
function dequeueRefreshToken(refreshToken) {
if (refreshTokenPromise[refreshToken].listeners > 1) {
refreshTokenPromise[refreshToken].listeners = refreshTokenPromise[refreshToken].listeners - 1;
return;
}
delete refreshTokenPromise[refreshToken];
}
This feels a bit too much like a hack, it also wouldn't solve the issue when the app runs in a cluster.
Does anyone know of a more robust solution to solve the issue?