Hi! I have a KMP app which on the home page sends ...
# ktor
v
Hi! I have a KMP app which on the home page sends multiple requests in parallel, I noticed that refresh tokens mechanism doesn’t work as expected, instead of sending one refresh token request and waiting for result it sends multiple at the same time, as a result the first one refreshes the token, but others fail, because refresh token has already been used. You can see it from network logs in the attached file. I use ktor 3.0.2. This is my code:
Copy code
runCatching {
                        co.touchlab.kermit.Logger.v(LOGGER_TAG, null) {
                            "Tokens update request"
                        }
                        val url = "https://${configuration.getBaseAuthUrl()}/application/o/token/"
                        client.submitForm(
                            url = url,
                            formParameters = parameters {
                                append("grant_type", "refresh_token")
                                append("client_id", "XXX")
                                append("refresh_token", oldTokens?.refreshToken ?: "")
                            }
                        ) { markAsRefreshTokenRequest() }.body<TokenInfo>()
                    }.fold(
                        onSuccess = { tokens ->
                            co.touchlab.kermit.Logger.v(LOGGER_TAG, null) {
                                "Tokens were successfully updated"
                            }
                            callback.onSuccess(
                                AuthTokens(
                                    idToken = tokens.idToken,
                                    accessToken = tokens.accessToken,
                                    refreshToken = tokens.refreshToken,
                                    accessTokenExpirationTime = Clock.System.now()
                                        .plus(tokens.expiresIn, DateTimeUnit.SECOND).toEpochMilliseconds()
                                )
                            )
                            BearerTokens(tokens.accessToken, tokens.refreshToken.orEmpty())
                        },
                        onFailure = {
                            co.touchlab.kermit.Logger.e(LOGGER_TAG, it) {
                                "Tokens update failed"
                            }
                            callback.onError(it)
                            null
                        }
                    )
                }
refresh_token_logs.txt
it’s not ktor issue, but my fault. I also suffer from this issue: https://youtrack.jetbrains.com/issue/KTOR-4759/Auth-BearerAuthProvider-caches-result-of-loadToken-until-process-death and I had my custom
Copy code
class BearerAuthProviderWithoutCaching(...) : AuthProvider
which doesn’t have
AuthTokenHolder
. Apparently, it breaks the logic. With default
BearerAuthConfig
it works correctly.
👀 1