Fetch access token Synchronously

According to the documentation, getCredentials should always return valid credentials. Therefore, it should not be necessary to implement an Authenticator, since Auth0 is taking care of refreshing the tokens inside the getCredentials call.

All you need to do is call getCredentials every time you’re making a call and pass the result to the header. For that, you still need to make the call “synchronous”. But that is entirely possible with Kotlin Coroutines:

suspend fun getAccessToken(): String {
        val credentials = suspendCoroutine<Credentials> { continuation ->
            credentialsManager.getCredentials(object : Callback<Credentials, CredentialsManagerException> {
                override fun onSuccess(result: Credentials) {
                    // Use credentials
                    continuation.resume(result)
                }

                override fun onFailure(error: CredentialsManagerException) {
                    // No credentials were previously saved or they couldn't be refreshed
                    continuation.resumeWithException(UnauthorizedException())
                }
            })
        }
        return credentials.accessToken
    }

Supposing OkHttp’s intercept() is being called on a background thread, you can call this function inside your interceptor like this:

  runBlocking {
            request.addHeader("Authorization", "Bearer ${LoginManager.getAccessToken()}")
        }
3 Likes