From 90a256c8f49c13fab4f825037a37e2fe37749f16 Mon Sep 17 00:00:00 2001 From: Waldemar Kornewald Date: Tue, 22 Oct 2024 17:32:05 +0200 Subject: [PATCH] Make re-auth status codes configurable Some services use 403 instead of 401. Changing them might be impossible. With this change Ktor can flexibly work with any broken service. --- .../common/src/io/ktor/client/plugins/auth/Auth.kt | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/ktor-client/ktor-client-plugins/ktor-client-auth/common/src/io/ktor/client/plugins/auth/Auth.kt b/ktor-client/ktor-client-plugins/ktor-client-auth/common/src/io/ktor/client/plugins/auth/Auth.kt index 1fd57fa6d25..44f94227e72 100644 --- a/ktor-client/ktor-client-plugins/ktor-client-auth/common/src/io/ktor/client/plugins/auth/Auth.kt +++ b/ktor-client/ktor-client-plugins/ktor-client-auth/common/src/io/ktor/client/plugins/auth/Auth.kt @@ -26,6 +26,7 @@ private class AtomicCounter { @KtorDsl public class AuthConfig { public val providers: MutableList = mutableListOf() + public val reAuthStatusCodes: MutableList = mutableListOf(HttpStatusCode.Unauthorized) } /** @@ -40,6 +41,7 @@ public val AuthCircuitBreaker: AttributeKey = AttributeKey("auth-request") * You can learn more from [Authentication and authorization](https://ktor.io/docs/auth.html). * * [providers] - list of auth providers to use. + * [reAuthStatusCodes] - list of [HttpStatusCode] values which trigger a re-auth. */ public val Auth: ClientPlugin = createClientPlugin("Auth", ::AuthConfig) { val providers = pluginConfig.providers.toList() @@ -128,14 +130,14 @@ public val Auth: ClientPlugin = createClientPlugin("Auth", ::AuthCon on(Send) { originalRequest -> val origin = proceed(originalRequest) - if (origin.response.status != HttpStatusCode.Unauthorized) return@on origin + if (origin.response.status !in pluginConfig.reAuthStatusCodes) return@on origin if (origin.request.attributes.contains(AuthCircuitBreaker)) return@on origin var call = origin val candidateProviders = HashSet(providers) - while (call.response.status == HttpStatusCode.Unauthorized) { + while (call.response.status in pluginConfig.reAuthStatusCodes) { LOGGER.trace("Received 401 for ${call.request.url}") val (provider, authHeader) = findProvider(call, candidateProviders) ?: run {