Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save tanishq14developer/67a7891a6713b82d96eb817818b2dfb6 to your computer and use it in GitHub Desktop.
Save tanishq14developer/67a7891a6713b82d96eb817818b2dfb6 to your computer and use it in GitHub Desktop.
An OkHttp Authenticator that performs token refreshes.
/**
* Authenticator that attempts to refresh the client's access token.
* In the event that a refresh fails and a new token can't be issued an error
* is delivered to the caller. This authenticator blocks all requests while a token
* refresh is being performed. In-flight requests that fail with a 401 are
* automatically retried.
*/
class AccessTokenAuthenticator(
private val tokenProvider: AccessTokenProvider
) : Authenticator {
override fun authenticate(route: Route?, response: Response): Request? {
// We need to have a token in order to refresh it.
val token = tokenProvider.token() ?: return null
synchronized(this) {
val newToken = tokenProvider.token()
// Check if the request made was previously made as an authenticated request.
if (response.request().header("Authorization") != null) {
// If the token has changed since the request was made, use the new token.
if (newToken != token) {
return response.request()
.newBuilder()
.removeHeader("Authorization")
.addHeader("Authorization", "Bearer $newToken")
.build()
}
val updatedToken = tokenProvider.refreshToken() ?: return null
// Retry the request with the new token.
return response.request()
.newBuilder()
.removeHeader("Authorization")
.addHeader("Authorization", "Bearer $updatedToken")
.build()
}
}
return null
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment