Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Correct way to retrigger loadTokens in Ktor client

In my mobile app, I have a singleton Ktor HttpClient with bearer authentication configured as such:

HttpClient(…) {
    install(Auth) {
        bearer {
            sendWithoutRequest { requestBuilder -> some condition }
            loadTokens(tokensStorage::getTokens)
            refreshTokens {
                performTokenRefresh(oldTokens.refreshToken)
            }
        }
    }
}

Now consider the following flow:

  1. The user opens the app while the tokens stored in my tokenStorage are not valid.
  2. The HttpClient loads the tokens from tokenStorage and the request fails with a 401.
  3. The HttpClient tries to perform a refresh but it fails too because the refresh token is invalid.
  4. The user is redirected to the login page, logs in, and the new valid tokens are stored in tokenStorage.
  5. Now from the app the user can retry the call that failed in points 2-3. However this will fail forever until the app is closed, because the HttpClient never tries to call loadTokens anymore. Indeed, as far as I can see from the source code, loadTokens is called only once and then never again.

I found out a couple of ways to solve the issue.

The first one is to manually retrieve BearerAuthProvider from the HttpClient and clear the token myself like in the following snippet, but it seems like a hacky workaround:

httpClient.plugin(Auth).providers
    .filterIsInstance<BearerAuthProvider>()
    .first().clearToken()

Another one is to manually load the current token from my tokenStorage in refreshToken and disregard what get passed in [email protected]:

refreshTokens {
    val currentRefreshToken = tokenStorage.getTokens().refreshToken
    performTokenRefresh(currentRefreshToken)
}

However this means that the client will do an unnecessary call to the refresh API, while having already a valid token pair (obtained from the login).

So my question is: is there a cleaner way to handle the situation? Am I misusing Ktor?

like image 355
gpunto Avatar asked Sep 10 '25 23:09

gpunto


1 Answers

We clear it manually in 2 places: We have the "Logout" use case which will be always triggered no matter if user logout manually or by 401 kick out. Because we need to clear other cached data as well. So the first lines of that logout use case is to notify the http client that whatever tokens it cached are not valid anymore.

fun invalidateAuthTokens() {

    val authProvider = httpClient.authProvider<BearerAuthProvider>()

    requireNotNull(authProvider)

    authProvider.clearToken()
}

You must make sure it will be called. We faced the case when we can open Login screen via app links, so potentially a user is logging while other user is still logged or the http client has empty tokens and doesn't know they are not valid. In that case we also needed to clear the cache on Login, so ktor's loadTokens{} called again when needed.

like image 67
Vladislav Avatar answered Sep 13 '25 15:09

Vladislav