Last active
November 5, 2020 16:45
-
-
Save PyvesB/3994f1feca44ce2b6d9d706b9cf98c76 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.text.ParseException; | |
import org.slf4j.Logger; | |
import org.slf4j.LoggerFactory; | |
import org.springframework.http.HttpHeaders; | |
import org.springframework.http.HttpMethod; | |
import org.springframework.http.HttpStatus; | |
import org.springframework.stereotype.Component; | |
import org.springframework.web.reactive.function.client.WebClient; | |
import org.springframework.web.reactive.function.client.WebClientResponseException.Unauthorized; | |
import me.vzhilin.auth.DigestAuthenticator; | |
import me.vzhilin.auth.parser.ChallengeResponse; | |
import reactor.core.publisher.Mono; | |
import reactor.util.retry.Retry; | |
@Component | |
public class DigestClient { | |
private static final Logger LOGGER = LoggerFactory.getLogger(DigestClient.class); | |
private final WebClient webClient; | |
private final DigestAuthenticator digestAuthenticator; | |
public DigestClient(WebClient webClient, DigestAuthenticator digestAuthenticator) { | |
this.webClient = webClient; | |
this.digestAuthenticator = digestAuthenticator; | |
} | |
public void get(String someUri) { | |
Mono.fromSupplier(() -> webClient | |
.get() | |
.uri(someUri) | |
.header(HttpHeaders.AUTHORIZATION, digestAuthenticator.autorizationHeader(HttpMethod.GET.name(), uri)) | |
.retrieve()) | |
.flatMap(response -> response.bodyToMono(String.class)) | |
.doOnNext(body -> LOGGER.info("Response for request {} was: {}", someUri, body)) | |
.doOnError(Unauthorized.class, response -> { | |
String authenticateHeader = response.getHeaders().getFirst(HttpHeaders.WWW_AUTHENTICATE); | |
try { | |
digestAuthenticator.onResponseReceived(ChallengeResponse.of(authenticateHeader), | |
HttpStatus.UNAUTHORIZED.value()); | |
} catch (ParseException e) { | |
LOGGER.error("Could not parse WWW-Authenticate header {}", authenticateHeader, e); | |
} | |
}) | |
.retryWhen(Retry.max(1).filter(t -> t instanceof Unauthorized)) | |
.subscribe(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment