Search in sources :

Example 1 with Authenticator

use of okhttp3.Authenticator in project azure-sdk-for-java by Azure.

the class KeyVaultCredentials method applyCredentialsFilter.

@Override
public void applyCredentialsFilter(OkHttpClient.Builder clientBuilder) {
    clientBuilder.addInterceptor(new Interceptor() {

        @Override
        public Response intercept(Chain chain) throws IOException {
            HttpUrl url = chain.request().url();
            Map<String, String> challengeMap = cache.getCachedChallenge(url);
            if (challengeMap != null) {
                // Get the bearer token
                String credential = getAuthenticationCredentials(challengeMap);
                Request newRequest = chain.request().newBuilder().header(AUTHENTICATE, BEARER_TOKEP_REFIX + credential).build();
                return chain.proceed(newRequest);
            } else {
                // response
                return chain.proceed(chain.request());
            }
        }
    });
    // Caches the challenge for failed request and re-send the request with
    // access token.
    clientBuilder.authenticator(new Authenticator() {

        @Override
        public Request authenticate(Route route, Response response) throws IOException {
            // if challenge is not cached then extract and cache it
            String authenticateHeader = response.header(WWW_AUTHENTICATE);
            Map<String, String> challengeMap = extractChallenge(authenticateHeader, BEARER_TOKEP_REFIX);
            // Cache the challenge
            cache.addCachedChallenge(response.request().url(), challengeMap);
            // Get the bearer token from the callback by providing the
            // challenges
            String credential = getAuthenticationCredentials(challengeMap);
            if (credential == null) {
                return null;
            }
            // be cached anywhere in our code.
            return response.request().newBuilder().header(AUTHENTICATE, BEARER_TOKEP_REFIX + credential).build();
        }
    });
}
Also used : Response(okhttp3.Response) Request(okhttp3.Request) IOException(java.io.IOException) Interceptor(okhttp3.Interceptor) Map(java.util.Map) HashMap(java.util.HashMap) HttpUrl(okhttp3.HttpUrl) Authenticator(okhttp3.Authenticator) Route(okhttp3.Route)

Example 2 with Authenticator

use of okhttp3.Authenticator in project okhttp by square.

the class RouteSelectorTest method explicitProxyTriesThatProxysAddressesOnly.

@Test
public void explicitProxyTriesThatProxysAddressesOnly() throws Exception {
    Address address = new Address(uriHost, uriPort, dns, socketFactory, null, null, null, authenticator, proxyA, protocols, connectionSpecs, proxySelector);
    RouteSelector routeSelector = new RouteSelector(address, routeDatabase);
    assertTrue(routeSelector.hasNext());
    dns.set(proxyAHost, dns.allocate(2));
    assertRoute(routeSelector.next(), address, proxyA, dns.lookup(proxyAHost, 0), proxyAPort);
    assertRoute(routeSelector.next(), address, proxyA, dns.lookup(proxyAHost, 1), proxyAPort);
    assertFalse(routeSelector.hasNext());
    dns.assertRequests(proxyAHost);
    // No proxy selector requests!
    proxySelector.assertRequests();
}
Also used : SocketAddress(java.net.SocketAddress) Address(okhttp3.Address) InetAddress(java.net.InetAddress) InetSocketAddress(java.net.InetSocketAddress) Test(org.junit.Test)

Example 3 with Authenticator

use of okhttp3.Authenticator in project okhttp by square.

the class URLConnectionTest method customTokenAuthenticator.

@Test
public void customTokenAuthenticator() throws Exception {
    MockResponse pleaseAuthenticate = new MockResponse().setResponseCode(401).addHeader("WWW-Authenticate: Bearer realm=\"oauthed\"").setBody("Please authenticate.");
    server.enqueue(pleaseAuthenticate);
    server.enqueue(new MockResponse().setBody("A"));
    RecordingOkAuthenticator authenticator = new RecordingOkAuthenticator("oauthed abc123");
    urlFactory.setClient(urlFactory.client().newBuilder().authenticator(authenticator).build());
    assertContent("A", urlFactory.open(server.url("/private").url()));
    assertNull(server.takeRequest().getHeader("Authorization"));
    assertEquals("oauthed abc123", server.takeRequest().getHeader("Authorization"));
    Response response = authenticator.onlyResponse();
    assertEquals("/private", response.request().url().url().getPath());
    assertEquals(Arrays.asList(new Challenge("Bearer", "oauthed")), response.challenges());
}
Also used : MockResponse(okhttp3.mockwebserver.MockResponse) MockResponse(okhttp3.mockwebserver.MockResponse) RecordingOkAuthenticator(okhttp3.internal.RecordingOkAuthenticator) Test(org.junit.Test)

Example 4 with Authenticator

use of okhttp3.Authenticator in project okhttp by square.

the class URLConnectionTest method doesNotAttemptAuthorization21Times.

@Test
public void doesNotAttemptAuthorization21Times() throws Exception {
    for (int i = 0; i < 21; i++) {
        server.enqueue(new MockResponse().setResponseCode(401));
    }
    String credential = Credentials.basic("jesse", "peanutbutter");
    urlFactory.setClient(urlFactory.client().newBuilder().authenticator(new RecordingOkAuthenticator(credential)).build());
    connection = urlFactory.open(server.url("/").url());
    try {
        connection.getInputStream();
        fail();
    } catch (ProtocolException expected) {
        assertEquals(401, connection.getResponseCode());
        assertEquals("Too many follow-up requests: 21", expected.getMessage());
    }
}
Also used : MockResponse(okhttp3.mockwebserver.MockResponse) SSLProtocolException(javax.net.ssl.SSLProtocolException) ProtocolException(java.net.ProtocolException) RecordingOkAuthenticator(okhttp3.internal.RecordingOkAuthenticator) Test(org.junit.Test)

Example 5 with Authenticator

use of okhttp3.Authenticator in project okhttp by square.

the class URLConnectionTest method authenticateWithGetAndTransparentGzip.

/** https://code.google.com/p/android/issues/detail?id=74026 */
@Test
public void authenticateWithGetAndTransparentGzip() throws Exception {
    MockResponse pleaseAuthenticate = new MockResponse().setResponseCode(401).addHeader("WWW-Authenticate: Basic realm=\"protected area\"").setBody("Please authenticate.");
    // fail auth three times...
    server.enqueue(pleaseAuthenticate);
    server.enqueue(pleaseAuthenticate);
    server.enqueue(pleaseAuthenticate);
    // ...then succeed the fourth time
    MockResponse successfulResponse = new MockResponse().addHeader("Content-Encoding", "gzip").setBody(gzip("Successful auth!"));
    server.enqueue(successfulResponse);
    Authenticator.setDefault(new RecordingAuthenticator());
    urlFactory.setClient(urlFactory.client().newBuilder().authenticator(new JavaNetAuthenticator()).build());
    connection = urlFactory.open(server.url("/").url());
    assertEquals("Successful auth!", readAscii(connection.getInputStream(), Integer.MAX_VALUE));
    // no authorization header for the first request...
    RecordedRequest request = server.takeRequest();
    assertNull(request.getHeader("Authorization"));
    // ...but the three requests that follow requests include an authorization header
    for (int i = 0; i < 3; i++) {
        request = server.takeRequest();
        assertEquals("GET / HTTP/1.1", request.getRequestLine());
        assertEquals("Basic " + RecordingAuthenticator.BASE_64_CREDENTIALS, request.getHeader("Authorization"));
    }
}
Also used : RecordedRequest(okhttp3.mockwebserver.RecordedRequest) MockResponse(okhttp3.mockwebserver.MockResponse) RecordingAuthenticator(okhttp3.internal.RecordingAuthenticator) Test(org.junit.Test)

Aggregations

Test (org.junit.Test)37 Request (okhttp3.Request)25 MockResponse (okhttp3.mockwebserver.MockResponse)23 Response (okhttp3.Response)22 OkHttpClient (okhttp3.OkHttpClient)19 RecordingOkAuthenticator (okhttp3.internal.RecordingOkAuthenticator)15 Authenticator (okhttp3.Authenticator)13 RecordedRequest (okhttp3.mockwebserver.RecordedRequest)13 IOException (java.io.IOException)12 Route (okhttp3.Route)10 BasicAuthenticator (com.burgstaller.okhttp.basic.BasicAuthenticator)9 CachingAuthenticator (com.burgstaller.okhttp.digest.CachingAuthenticator)8 DigestAuthenticator (com.burgstaller.okhttp.digest.DigestAuthenticator)8 RecordingAuthenticator (okhttp3.internal.RecordingAuthenticator)6 Credentials (com.burgstaller.okhttp.digest.Credentials)5 InetSocketAddress (java.net.InetSocketAddress)5 Interceptor (okhttp3.Interceptor)5 InetAddress (java.net.InetAddress)4 SocketAddress (java.net.SocketAddress)4 ConcurrentHashMap (java.util.concurrent.ConcurrentHashMap)4