Graceful refresh of auth token with External Ident...
# support
n
How would I gracefully re-auth through the refresh token prior to access token expiration when using the External Identity Providers flow? I see this doc https://www.medplum.com/docs/api/oauth/token#exchanging-a-refresh-token-for-tokens which would lead me to believe that I need to setup an endpoint that uses a medplum admin client to exchange the refresh token for a new access token. Are there helper methods to make swapping the new token values on the non-admin client easier?
FWIW, I know that I can decode the existing access token to get the
exp
value to setup some sort of timer to perform refresh prior to expiration.
hmm seems like the medplum client already attempts to refresh the tokens on an unauthenticated request https://github.com/medplum/medplum/blob/af97ce40b135d1ef64a658f056cc945a9970e613/packages/core/src/client.ts#L3001-L3014
Is a non-admin client able to refresh it's own access token?
r
@node yes I believe it should be able to. Is there an issue with how refresh tokens are handled?
n
It seems so - when I make the following request with a non-admin medplum client (refreshing itself), I get an error
Copy code
ts
medplum.post(
  '/oauth2/token',
  `grant_type=refresh_token&refresh_token=${medplum.getActiveLogin().refreshToken}`,
  'application/x-www-form-urlencoded',
)
Copy code
sh
Error: {"error":"invalid_request","error_description":"Invalid authorization header"}
But if I make the same request with an admin client, it works and a new access token is granted
r
@node we just made some changes to the refresh token https://github.com/medplum/medplum/pull/3681/files. Do these address the problem at all?
n
Hey Rahul, unfortunately not because I have an Apollo client that is polling and I hit an unauthed error in that client prior to the medplum client. I could just invoke the medplum client in an apollo client middleware to cause the refresh but this feels a bit odd. I've setup a system that automatically refreshes the tokens prior to their expiration and I have activity tracking to logout at a set interval of inactivity. I've also setup an endpoint that allows refreshing using an admin medplum client as I couldn't figure out how to resolve the error I was seeing with non-admin clients refreshing their own tokens.
I did some more testing on this and I was able to get a non-admin client to refresh its own token
155 Views