I'm using the Ktor client in a CMP app. I'm using ...
# ktor
r
I'm using the Ktor client in a CMP app. I'm using the Auth0 SDK for authentication. Given that I'm already caching the bearer token using the Auth0 SDK, should I turn Ktor caching off?
Copy code
bearer {
    cacheTokens = false
}
Doc guidance says: > Disabling token caching is especially useful when authentication data changes frequently or must reflect the most recent state. > https://ktor.io/docs/client-auth.html#controlling-caching-behavior My use case also feels like a good scenario to turn off caching. I don't see a reason to double cache.
a
Can you please share the client code where the Bearer provider of the Auth plugin is used?
r
Sure 🙂 Auth plugin extension function:
Copy code
import io.ktor.client.HttpClientConfig
import io.ktor.client.plugins.auth.Auth
import io.ktor.client.plugins.auth.providers.bearer

internal fun HttpClientConfig<*>.installAuthPlugin(/* ... */) {
    install(Auth) {
        bearer {
            loadTokens {
                // Load token from Auth0 interface...
            }
            refreshTokens {
                // Refresh token from Auth0 interface...
            }
        }
    }
}
Providing HttpClient to the DI container:
Copy code
import dev.zacsweers.metro.AppScope
import dev.zacsweers.metro.ContributesTo
import dev.zacsweers.metro.Provides
import io.ktor.client.HttpClient

@ContributesTo(AppScope::class)
interface NetworkProvider {

    @Provides
    fun providesHttpClient(/* ... */): HttpClient =
        HttpClient(platformEngineFactory()) {
            installAuthPlugin(/* ... */)
            // ...
        }
}
I'm using the Auth0 Credentials Manager so getting the latest token involves calling (simplified):
Copy code
try {
    val credentials = manager.awaitCredentials()
    println(credentials)
} catch (e: CredentialsManagerException) {
    e.printStacktrace()
}
If the token is expired, it gets a new one and saves it to local storage.
a
For such a case, it's recommended to disable Ktor's caching; otherwise,
loadTokens
may not be called when necessary to trigger the Auth0 functionality.
thank you color 1