Search in sources :

Example 51 with Authenticator

use of okhttp3.Authenticator in project collect by opendatakit.

the class OkHttpOpenRosaServerClientProvider method createNewClient.

@NonNull
private OkHttpOpenRosaServerClient createNewClient(String scheme, String userAgent, @Nullable HttpCredentialsInterface credentials) {
    OkHttpClient.Builder builder = baseClient.newBuilder().connectTimeout(CONNECTION_TIMEOUT, TimeUnit.MILLISECONDS).writeTimeout(WRITE_CONNECTION_TIMEOUT, TimeUnit.MILLISECONDS).readTimeout(READ_CONNECTION_TIMEOUT, TimeUnit.MILLISECONDS).followRedirects(true);
    // 7.0 and 7.1 (API 24/25) use network_security_config to get support.
    if (Build.VERSION.SDK_INT <= 23) {
        try {
            addTrustForLetsEncryptRoot(builder);
        } catch (CertificateException e) {
            Timber.w(e, "Failure attempting to add Let's Encrypt root");
        }
    }
    if (credentials != null) {
        Credentials cred = new Credentials(credentials.getUsername(), credentials.getPassword());
        DispatchingAuthenticator.Builder daBuilder = new DispatchingAuthenticator.Builder();
        daBuilder.with("digest", new DigestAuthenticator(cred));
        if (scheme.equalsIgnoreCase("https")) {
            daBuilder.with("basic", new BasicAuthenticator(cred));
        }
        DispatchingAuthenticator authenticator = daBuilder.build();
        ConcurrentHashMap<String, CachingAuthenticator> authCache = new ConcurrentHashMap<>();
        builder.authenticator(new CachingAuthenticatorDecorator(authenticator, authCache)).addInterceptor(new AuthenticationCacheInterceptor(authCache)).build();
    }
    return new OkHttpOpenRosaServerClient(builder.build(), userAgent);
}
Also used : OkHttpClient(okhttp3.OkHttpClient) CachingAuthenticator(com.burgstaller.okhttp.digest.CachingAuthenticator) CachingAuthenticatorDecorator(com.burgstaller.okhttp.CachingAuthenticatorDecorator) CertificateException(java.security.cert.CertificateException) DispatchingAuthenticator(com.burgstaller.okhttp.DispatchingAuthenticator) BasicAuthenticator(com.burgstaller.okhttp.basic.BasicAuthenticator) DigestAuthenticator(com.burgstaller.okhttp.digest.DigestAuthenticator) AuthenticationCacheInterceptor(com.burgstaller.okhttp.AuthenticationCacheInterceptor) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) Credentials(com.burgstaller.okhttp.digest.Credentials) NonNull(androidx.annotation.NonNull)

Example 52 with Authenticator

use of okhttp3.Authenticator in project keepass2android by PhilippC.

the class WebDavStorage method getClient.

private OkHttpClient getClient(ConnectionInfo ci) throws NoSuchAlgorithmException, KeyManagementException, KeyStoreException {
    OkHttpClient.Builder builder = new OkHttpClient.Builder();
    final Map<String, CachingAuthenticator> authCache = new ConcurrentHashMap<>();
    com.burgstaller.okhttp.digest.Credentials credentials = new com.burgstaller.okhttp.digest.Credentials(ci.username, ci.password);
    final BasicAuthenticator basicAuthenticator = new BasicAuthenticator(credentials);
    final DigestAuthenticator digestAuthenticator = new DigestAuthenticator(credentials);
    // note that all auth schemes should be registered as lowercase!
    DispatchingAuthenticator authenticator = new DispatchingAuthenticator.Builder().with("digest", digestAuthenticator).with("basic", basicAuthenticator).build();
    builder = builder.authenticator(new CachingAuthenticatorDecorator(authenticator, authCache)).addInterceptor(new AuthenticationCacheInterceptor(authCache));
    if ((mCertificateErrorHandler != null) && (!mCertificateErrorHandler.alwaysFailOnValidationError())) {
        TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
        trustManagerFactory.init((KeyStore) null);
        TrustManager[] trustManagers = trustManagerFactory.getTrustManagers();
        if (trustManagers.length != 1 || !(trustManagers[0] instanceof X509TrustManager)) {
            throw new IllegalStateException("Unexpected default trust managers:" + Arrays.toString(trustManagers));
        }
        X509TrustManager trustManager = (X509TrustManager) trustManagers[0];
        trustManager = new DecoratedTrustManager(trustManager, mCertificateErrorHandler);
        SSLContext sslContext = SSLContext.getInstance("TLS");
        sslContext.init(null, new TrustManager[] { trustManager }, null);
        SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();
        builder = builder.sslSocketFactory(sslSocketFactory, trustManager).hostnameVerifier(new DecoratedHostnameVerifier(OkHostnameVerifier.INSTANCE, mCertificateErrorHandler));
    }
    OkHttpClient client = builder.build();
    return client;
}
Also used : OkHttpClient(okhttp3.OkHttpClient) DispatchingAuthenticator(com.burgstaller.okhttp.DispatchingAuthenticator) BasicAuthenticator(com.burgstaller.okhttp.basic.BasicAuthenticator) AuthenticationCacheInterceptor(com.burgstaller.okhttp.AuthenticationCacheInterceptor) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) SSLSocketFactory(javax.net.ssl.SSLSocketFactory) CachingAuthenticator(com.burgstaller.okhttp.digest.CachingAuthenticator) CachingAuthenticatorDecorator(com.burgstaller.okhttp.CachingAuthenticatorDecorator) SSLContext(javax.net.ssl.SSLContext) TrustManager(javax.net.ssl.TrustManager) DecoratedTrustManager(keepass2android.javafilestorage.webdav.DecoratedTrustManager) X509TrustManager(javax.net.ssl.X509TrustManager) DecoratedHostnameVerifier(keepass2android.javafilestorage.webdav.DecoratedHostnameVerifier) DecoratedTrustManager(keepass2android.javafilestorage.webdav.DecoratedTrustManager) DigestAuthenticator(com.burgstaller.okhttp.digest.DigestAuthenticator) X509TrustManager(javax.net.ssl.X509TrustManager) TrustManagerFactory(javax.net.ssl.TrustManagerFactory)

Example 53 with Authenticator

use of okhttp3.Authenticator in project okhttp-digest by rburgst.

the class AuthenticationCacheInterceptorTest method testCaching_withDifferentPorts.

@Test
public void testCaching_withDifferentPorts() throws Exception {
    Map<String, CachingAuthenticator> authCache = new ConcurrentHashMap<>();
    // Fill in authCache.
    // https://myhost.com => basic auth user1:user1
    givenCachedAuthenticationFor("https://myhost.com", authCache);
    assertEquals(1, authCache.size());
    Interceptor interceptor = new AuthenticationCacheInterceptor(authCache);
    // Check that authenticator exists for https://myhost.com:443
    final String authorization = whenInterceptAuthenticationForUrl(interceptor, "https://myhost.com:443");
    thenAuthorizationHeaderShouldBePresent(authorization);
    // Check that authenticator does not exist for http://myhost.com:8080
    final String authorization2 = whenInterceptAuthenticationForUrl(interceptor, "http://myhost.com:8080");
    thenNoAuthorizationHeaderShouldBePresent(authorization2);
}
Also used : CachingAuthenticator(com.burgstaller.okhttp.digest.CachingAuthenticator) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) Interceptor(okhttp3.Interceptor) Test(org.junit.Test)

Example 54 with Authenticator

use of okhttp3.Authenticator in project okhttp-digest by rburgst.

the class AuthenticationCacheInterceptorTest method testCaching_withExpiredAuthentication.

@Test
public void testCaching_withExpiredAuthentication() throws Exception {
    Map<String, CachingAuthenticator> authCache = new ConcurrentHashMap<>();
    final String dummyUrl = "https://myhost.com/path";
    // Fill in authCache.
    // https://myhost.com => basic auth user1:user1
    givenCachedAuthenticationFor(dummyUrl, authCache);
    assertThat(authCache).hasSize(1);
    Interceptor interceptor = new AuthenticationCacheInterceptor(authCache);
    // Check that unauthorized response (e.g. credentials changed or expired)
    // removes cached authenticator
    whenServerReturns401(dummyUrl, interceptor);
    thenAuthCacheShouldBeEmpty(authCache);
}
Also used : CachingAuthenticator(com.burgstaller.okhttp.digest.CachingAuthenticator) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) Interceptor(okhttp3.Interceptor) Test(org.junit.Test)

Example 55 with Authenticator

use of okhttp3.Authenticator in project okhttp-digest by rburgst.

the class DispatchingAuthenticatorTest method testAuthenticateWithState__shouldCallAuthenticatorsInExpectedOrder.

/**
 * Makes sure that in the case of cached authenticators the authenticators are called in the
 * order in which they were registered.
 *
 * @throws Exception
 */
@Test
public void testAuthenticateWithState__shouldCallAuthenticatorsInExpectedOrder() throws Exception {
    // given
    CachingAuthenticator auth1 = mock(CachingAuthenticator.class);
    CachingAuthenticator auth2 = mock(CachingAuthenticator.class);
    DispatchingAuthenticator authenticator = new DispatchingAuthenticator.Builder().with("digest", auth1).with("basic", auth2).build();
    Request request = createDummyRequest();
    // make sure that the 2nd authenticator will not be called
    given(auth2.authenticateWithState(eq(mockRoute), eq(request))).willThrow(IllegalStateException.class);
    given(auth1.authenticateWithState(eq(mockRoute), eq(request))).willReturn(request);
    // when
    Request result = authenticator.authenticateWithState(mockRoute, request);
    // then
    assertEquals(request, result);
}
Also used : CachingAuthenticator(com.burgstaller.okhttp.digest.CachingAuthenticator) Request(okhttp3.Request) Test(org.junit.Test)

Aggregations

Test (org.junit.Test)37 Request (okhttp3.Request)27 OkHttpClient (okhttp3.OkHttpClient)26 Response (okhttp3.Response)24 MockResponse (okhttp3.mockwebserver.MockResponse)23 Authenticator (okhttp3.Authenticator)20 IOException (java.io.IOException)15 RecordingOkAuthenticator (okhttp3.internal.RecordingOkAuthenticator)15 RecordedRequest (okhttp3.mockwebserver.RecordedRequest)13 Route (okhttp3.Route)12 BasicAuthenticator (com.burgstaller.okhttp.basic.BasicAuthenticator)9 DigestAuthenticator (com.burgstaller.okhttp.digest.DigestAuthenticator)8 CachingAuthenticator (com.burgstaller.okhttp.digest.CachingAuthenticator)7 InetSocketAddress (java.net.InetSocketAddress)7 RecordingAuthenticator (okhttp3.internal.RecordingAuthenticator)6 Credentials (com.burgstaller.okhttp.digest.Credentials)5 InetAddress (java.net.InetAddress)5 Proxy (java.net.Proxy)5 Interceptor (okhttp3.Interceptor)5 HttpLoggingInterceptor (okhttp3.logging.HttpLoggingInterceptor)5