Hi, I need suggestions how to implement oauth refr...
# getting-started
s
Hi, I need suggestions how to implement oauth refresh token periodically with coroutines. I want to refresh the token before the client throws unauthorized exception, i'm using ktor client in intellij plugin. I have a ktor client that is initialized with an account and credentials , upon initialization i want to start a task that will wait for expiration time - 5.minutes, refresh the token and start a new task for the next refresh. something like that: launch{ val timeLeft = computeTimeLeft(currentCredentials) - 5.minutes delay(timeLeft) retry(3.times, withDelay 30.seconds){ val newCredentials = refreshToken(currentCredentials) if(newCredentials != null){ currentCredentials = newCredentials } } onSuccess{ start a new task for the next refresh } } does it makes sense to do a while(true) loop in coroutime ? launch{ while(true){ val timeLeft = computeTimeLeft(currentCredentials) - 5.minutes delay(timeLeft) retry(3.times, withDelay 30.seconds){ val newCredentials = refreshToken(currentCredentials) if(newCredentials != null){ currentCredentials = newCredentials } } }
a
Why like this? If you have the refresh token just get a new token after the access token has expired.
s
because of this reason: when ktor client gets an unauthorized response it will invoke a callback to refresh the token and execute the request again. but I'm experiencing failures in refresh token from our server, so if the refresh fails, the request will fail. refreshing before expiration gives the opportunity to retry a few times with a long delay. if i retry on unauthorized response the request may take too long to complete.
a
This sounds like you’re solving another problem with a complicated hack. Why do the refresh token requests fail? Solve that and you’re implementing everything correctly instead of adding a layer of complication
plus1 3
s
You're right, I will just refresh on unauthorized response. Thanks