kotlinktorktor-client

How to handle an expired refresh token in ktor?


I use bearer and refresh tokens in ktor as described Here https://ktor.io/docs/client-bearer-auth.html

What ist not mentioned in the docs is how the ktor auth module behaves when a token refresh ist required but the refresh token ist expired as well.

I'd like to send the user to the login page when the refresh token ist expired but I don't know how


Solution

  • HttpClient.kt

    val client = HttpClient {
        install(Auth) {
            bearer {
                loadTokens {
                    BearerTokens(
                        accessToken = getStoredAccessToken(),
                        refreshToken = getStoredRefreshToken()
                    )
                }
                refreshTokens {
                    try {
                        // Attempt to refresh tokens
                        val newTokens = refreshTokensFromServer(oldTokens)
                        BearerTokens(newTokens.accessToken, newTokens.refreshToken)
                    } catch (e: RefreshTokenExpiredException) {
                        // Handle expired refresh token
                        navigateToLogin()
                        null // Return null to indicate authentication failure
                    }
                }
            }
        }
    }
    

    You can create a custom exception handler or use Ktor's plugin system to intercept authentication failures. When the refresh token is expired, trigger navigation to your login page through your app's navigation system. The key is returning null in the refreshTokens block when the refresh fails, which will cause the authentication to fail and stop further request attempts.