https://kotlinlang.org logo
#server
Title
# server
t

Tony Thomas

01/08/2023, 4:56 PM
Hey team. We were trying to write an automatic retry on 5xx when using the ReactiveAuthenticationManager, with authentication handled via an API call. We came up with something like this to override the
authenticate
with. Do you people see any potential issues with it ?
Copy code
class ServiceException(message: String?, var statusCode: Int) : RuntimeException(message) {
    init {
      statusCode = statusCode
    }
  }
  
fun doAsyncAuthentication(
    url: HttpUrl,
  ): Mono<Authentication> {
    return webClient
      .post()
      .uri(url.toUri())
      .body(BodyInserters.fromFormData("token", "tokenValue"))
      .retrieve()
      .onStatus(HttpStatus::is4xxClientError) { response ->
        response
          .createException()
          .map { InvalidBearerTokenException(it) }
      }
      .onStatus(HttpStatus::is5xxServerError) { response ->
        Mono.error(ServiceException("Server error", response.rawStatusCode()))
      }
      .bodyToMono<TokenInfoResponse>()
      .retryWhen(Retry
        .backoff(3, Duration.ofSeconds(1))
        .filter { throwable -> throwable is ServiceException })
      .map {
        OurAuthenticationResponse(it.clientId, it.scopes)
      }
  }
8 Views