Hey I'm using Ktor in my Android app for API calls...
# ktor
v
Hey I'm using Ktor in my Android app for API calls. When my profile API request returns
401 Unauthorized
, I attempt to refresh the token. The refresh token API call succeeds, but when I retry the profile API call, it still returns
401
.
Here’s my flow: 1. Profile API call → 401 2. Trigger refresh token API → Success (new access token received) 3. Retry profile API call → Still 401 It seems the new token isn’t being used correctly, or the server is rejecting it. How can I detect this issue and log out the user after repeated 401 responses?
Here’s my Ktor client setup:
Copy code
val client = HttpClient {
    install(Auth) {
        bearer {
            refreshTokens {
                val newToken = refreshAccessToken() // Calls refresh API
                if (newToken != null) {
                    TokenStorage.saveTokens(newToken) // Save new token
                    newToken
                } else {
                    logOutUser() 
                }
            }
        }
    }
}
Even after the refresh, the next request still gets a
401
. How should I handle this scenario to force a logout when token refresh fails or the server keeps rejecting requests?
l
inside the Auth scope you need to pass the tokens like so:
Copy code
bearer {
  loadTokens {
    BearerTokens(
      accessToken = //get from your storage
      refreshToken = //get from your storage
    )
  }
}
v
but how do i handle 401?
l
The lamba you installed (
refreshTokens
) gets called when your api returns 401, so you can renew the tokens and try again
k
You can have a variable to track the number of retries, check if the counter is 2 then you can trigger the logout event
b
Copy code
install(Auth){
     bearer {
            loadTokens {
                    BearerTokens(accessToken,refreshToken)
            }

            refreshTokens {
            		// Calls refresh API
            		val newToken = refreshAccessToken()
                    if (newToken != null) {
                    	// Save new token
                        TokenStorage.saveTokens(newToken)
                        // Pass new accessToken
                        BearerTokens(newToken,refreshToken) 
                    } else 
                    	logOutUser() 
                        
                }
    }
}
v
thanks Kibet, but I'm looking for inbuilt function who can found out how many times api retried.
👍 1
k
@Vivek Modi not sure if you found a way to approach this, but just came across this. You can check if it will work
Copy code
install(HttpRequestRetry) {
            retryOnServerErrors(maxRetries = 5)
            delayMillis { retry ->
                retry * 2000L
            }
        }