I have a scenario where the refresh token fetch periodically fails. Keycloak is the oidc provider, using code flow from a web app. When the access token has expired, the back-end application reaches out to the keycloak token endpoint for a new one using the refresh token - generally, this works. Intermittently, however, the refresh token fails, with "invalid_grant, Token is not active". From everything I've found on SO and elsewhere this is due to clock drift. It's certainly possible, this is all running in containers on VMs on systems I do not control, and I would like to mitigate for the situation.
The system in place actually fails pretty gracefully - just not with an XHR. So if I navigate between logical pages in my single page application, and this scenario occurs, the user does not see anything amiss. When a background fetch happens the user sees an error, but the next request succeeds - here's the sequence of requests that causes it:
/<original-request-endpoint> 302, invalid token, redirect to keycloak auth endpoint for the realm for the user to sign in. The redirect is my logic: if the user is not authenticated, send them to the login page.
/keycloak/...realm/.../auth 302 - the user's session is actually still valid, redirect to my authorization endpoint on the back end with a code.
/authorize 302 - this gets a new access token from the keycloak token endpoint and sets the cookie, so future requests succeed with the new token. Redirect to the landing page.
/landing this is effectively ignored.
I was thinking of trying to duplicate the keycloak auth request on the back end if the token refresh fails - but I don't like that idea, it feels messy, I'll need to reconstruct all the request context (cookies etc.) for this special scenario.
Any idea what I'm doing wrong or a better approach to handling refresh token failure?