11package info .unterrainer .commons .restclient ;
22
33import java .io .IOException ;
4+ import java .util .Map ;
45import java .util .Random ;
6+ import java .util .concurrent .ConcurrentHashMap ;
57import java .util .concurrent .TimeUnit ;
68
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+
717import info .unterrainer .commons .restclient .exceptions .RestClientException ;
818import info .unterrainer .commons .serialization .jsonmapper .JsonMapper ;
919import lombok .experimental .Accessors ;
1020import lombok .extern .slf4j .Slf4j ;
1121import okhttp3 .Call ;
12- import okhttp3 .Credentials ;
1322import okhttp3 .Headers ;
1423import okhttp3 .MediaType ;
1524import okhttp3 .OkHttpClient ;
@@ -25,6 +34,7 @@ public class RestClient {
2534 private final Random random = new Random ();
2635
2736 protected OkHttpClient client ;
37+ protected final Map <String , CachingAuthenticator > authCache = new ConcurrentHashMap <>();
2838 protected final JsonMapper jsonMapper ;
2939
3040 public RestClient (final JsonMapper jsonMapper ) {
@@ -50,11 +60,20 @@ public RestClient(final JsonMapper jsonMapper, final String userName, final Stri
5060 .writeTimeout (writeTimeoutInMillis , TimeUnit .MILLISECONDS )
5161 .addInterceptor (new GzipInterceptor ())
5262 .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- });
63+ if (userName != null || password != null ) {
64+ Credentials credentials = new Credentials (userName , password );
65+ final BasicAuthenticator basicAuthenticator = new BasicAuthenticator (credentials );
66+ final DigestAuthenticator digestAuthenticator = new DigestAuthenticator (credentials );
67+
68+ // Note that all authentication schemes should be registered as lower-case!
69+ DispatchingAuthenticator authenticator = new DispatchingAuthenticator .Builder ()
70+ .with ("digest" , digestAuthenticator )
71+ .with ("basic" , basicAuthenticator )
72+ .build ();
73+
74+ c .authenticator (new CachingAuthenticatorDecorator (authenticator , authCache ))
75+ .addInterceptor (new AuthenticationCacheInterceptor (authCache ));
76+ }
5877 client = c .build ();
5978 }
6079
0 commit comments