I have httpClient with OAuth (using auth Plugin) w...
# ktor
m
I have httpClient with OAuth (using auth Plugin) when it does the refresh call it also includes the previous expired bearer token. This makes the refresh fail. I can't seem to prevent that header from being sent. Any ideas?
Copy code
internal val someClient = HttpClient(CIO) {
    expectSuccess = true

    install(ContentNegotiation) {
        json(Json {
            ignoreUnknownKeys = true
        })
    }

    install(HttpRequestRetry) {
        retryOnServerErrors(maxRetries = 5)
        retryIf(5) { _, response -> // RATE LIMITING
            response.status.value == 429
        }
        exponentialDelay()
    }

    install(Auth) {
        bearer {
            this.loadTokens {
                bearerToken
            }
            // Configure bearer authentication
            refreshTokens {
                bearerToken =
                    getAccessToken(client) {
                        markAsRefreshTokenRequest()
// Tried this but header is still sent
//                        headers {
//                            remove(HttpHeaders.Authorization)
//                        }
                    }
                bearerToken
            }

            sendWithoutRequest { _ ->
                true
            }
        }
    }

    install(Logging) {
        level = LogLevel.HEADERS
    }
}

private suspend fun getAccessToken(
    client: HttpClient,
    f: HttpRequestBuilder.() -> Unit = { }
): BearerTokens {
    println("Getting access token")
    val tokenInfo: TokenInfo = client.submitForm(
        url = "<https://example.com/identity/token>",
        formParameters = parameters {
            append("grant_type", "client_credentials")
            append("scope", "get")
            append("client_id", "clietnId")
            append("client_secret", "clientSecret")
        },
        block = f
    ).body<TokenInfo>()

    return BearerTokens(tokenInfo.accessToken, tokenInfo.refreshToken)
}
I use a different client for the tokens. That seems to work well
Copy code
install(Auth) {
        bearer {
            loadTokens {
                getAccessToken(tokenClient)
            }
            refreshTokens {
                getAccessToken(tokenClient) {
                    markAsRefreshTokenRequest()
                }
            }
            sendWithoutRequest { _ ->
                true
            }
        }
    }
}
a
Also, you can clear the tokens before making the refresh token request to avoid sending the expired token. You can follow KTOR-8107 for updates, which would resolve your use-case.
👍 1