Skip to content

Commit

Permalink
Make re-auth status codes configurable
Browse files Browse the repository at this point in the history
Some services use 403 instead of 401. Changing them might be impossible. With this change Ktor can flexibly work with any broken service.
  • Loading branch information
wkornewald committed Oct 22, 2024
1 parent 3d71a28 commit 90a256c
Showing 1 changed file with 4 additions and 2 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ private class AtomicCounter {
@KtorDsl
public class AuthConfig {
public val providers: MutableList<AuthProvider> = mutableListOf()
public val reAuthStatusCodes: MutableList<HttpStatusCode> = mutableListOf(HttpStatusCode.Unauthorized)
}

/**
Expand All @@ -40,6 +41,7 @@ public val AuthCircuitBreaker: AttributeKey<Unit> = 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<AuthConfig> = createClientPlugin("Auth", ::AuthConfig) {
val providers = pluginConfig.providers.toList()
Expand Down Expand Up @@ -128,14 +130,14 @@ public val Auth: ClientPlugin<AuthConfig> = 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 {
Expand Down

0 comments on commit 90a256c

Please sign in to comment.