|
1 | 1 | package info.unterrainer.commons.restclient; |
2 | 2 |
|
3 | 3 | import java.io.IOException; |
| 4 | +import java.util.Map; |
4 | 5 | import java.util.Random; |
| 6 | +import java.util.concurrent.ConcurrentHashMap; |
5 | 7 | import java.util.concurrent.TimeUnit; |
6 | 8 |
|
| 9 | +import com.burgstaller.okhttp.AuthenticationCacheInterceptor; |
| 10 | +import com.burgstaller.okhttp.CachingAuthenticatorDecorator; |
| 11 | +import com.burgstaller.okhttp.DispatchingAuthenticator; |
| 12 | +import com.burgstaller.okhttp.basic.BasicAuthenticator; |
| 13 | +import com.burgstaller.okhttp.digest.CachingAuthenticator; |
| 14 | +import com.burgstaller.okhttp.digest.Credentials; |
| 15 | +import com.burgstaller.okhttp.digest.DigestAuthenticator; |
| 16 | + |
7 | 17 | import info.unterrainer.commons.restclient.exceptions.RestClientException; |
8 | 18 | import info.unterrainer.commons.serialization.jsonmapper.JsonMapper; |
9 | 19 | import lombok.experimental.Accessors; |
10 | 20 | import lombok.extern.slf4j.Slf4j; |
11 | 21 | import okhttp3.Call; |
12 | | -import okhttp3.Credentials; |
13 | 22 | import okhttp3.Headers; |
14 | 23 | import okhttp3.MediaType; |
15 | 24 | import okhttp3.OkHttpClient; |
@@ -50,11 +59,22 @@ public RestClient(final JsonMapper jsonMapper, final String userName, final Stri |
50 | 59 | .writeTimeout(writeTimeoutInMillis, TimeUnit.MILLISECONDS) |
51 | 60 | .addInterceptor(new GzipInterceptor()) |
52 | 61 | .followRedirects(true); |
53 | | - if (userName != null || password != null) |
54 | | - c.authenticator((route, response) -> { |
55 | | - String credential = Credentials.basic(userName, password); |
56 | | - return response.request().newBuilder().header("Authorization", credential).build(); |
57 | | - }); |
| 62 | + if (userName != null || password != null) { |
| 63 | + final Map<String, CachingAuthenticator> authCache = new ConcurrentHashMap<>(); |
| 64 | + |
| 65 | + Credentials credentials = new Credentials(userName, password); |
| 66 | + final BasicAuthenticator basicAuthenticator = new BasicAuthenticator(credentials); |
| 67 | + final DigestAuthenticator digestAuthenticator = new DigestAuthenticator(credentials); |
| 68 | + |
| 69 | + // note that all auth schemes should be registered as lowercase! |
| 70 | + DispatchingAuthenticator authenticator = new DispatchingAuthenticator.Builder() |
| 71 | + .with("digest", digestAuthenticator) |
| 72 | + .with("basic", basicAuthenticator) |
| 73 | + .build(); |
| 74 | + |
| 75 | + c.authenticator(new CachingAuthenticatorDecorator(authenticator, authCache)) |
| 76 | + .addInterceptor(new AuthenticationCacheInterceptor(authCache)); |
| 77 | + } |
58 | 78 | client = c.build(); |
59 | 79 | } |
60 | 80 |
|
|
0 commit comments