Skip to content

Instantly share code, notes, and snippets.

@lordcodes
Created March 17, 2020 09:31
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lordcodes/f68da5178cb440cfdc4ee2b5c85dce2b to your computer and use it in GitHub Desktop.
Save lordcodes/f68da5178cb440cfdc4ee2b5c85dce2b to your computer and use it in GitHub Desktop.
Code for the article: "Authorization and retrying of web requests for OkHttp and Retrofit"
class TokenRefreshAuthenticator(
private val authorizationRepository: AuthorizationRepository
) : Authenticator {
override fun authenticate(route: Route?, response: Response): Request? = when {
response.retryCount > 2 -> null
else -> response.createSignedRequest()
}
private fun Response.createSignedRequest(): Request? = try {
val accessToken = authenticationRepository.fetchFreshAccessToken()
request.signWithToken(accessToken)
} catch (error: Throwable) {
Logger.error(error, "Failed to re-sign request")
null
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment