Search in sources :

Example 1 with Challenge

use of okhttp3.Challenge 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 Challenge

use of okhttp3.Challenge in project okhttp by square.

the class ResponseCacheTest method assertCached.

private void assertCached(boolean shouldPut, int responseCode) throws Exception {
    int expectedResponseCode = responseCode;
    server = new MockWebServer();
    MockResponse mockResponse = new MockResponse().addHeader("Last-Modified: " + formatDate(-1, TimeUnit.HOURS)).addHeader("Expires: " + formatDate(1, TimeUnit.HOURS)).setResponseCode(responseCode).setBody("ABCDE").addHeader("WWW-Authenticate: challenge");
    if (responseCode == HttpURLConnection.HTTP_PROXY_AUTH) {
        mockResponse.addHeader("Proxy-Authenticate: Basic realm=\"protected area\"");
    } else if (responseCode == HttpURLConnection.HTTP_UNAUTHORIZED) {
        mockResponse.addHeader("WWW-Authenticate: Basic realm=\"protected area\"");
    } else if (responseCode == HttpURLConnection.HTTP_NO_CONTENT || responseCode == HttpURLConnection.HTTP_RESET) {
        // We forbid bodies for 204 and 205.
        mockResponse.setBody("");
    }
    server.enqueue(mockResponse);
    if (responseCode == HttpURLConnection.HTTP_CLIENT_TIMEOUT) {
        // 408's are a bit of an outlier because we may repeat the request if we encounter this
        // response code. In this scenario, there are 2 responses: the initial 408 and then the 200
        // because of the retry. We just want to ensure the initial 408 isn't cached.
        expectedResponseCode = 200;
        server.enqueue(new MockResponse().setHeader("Cache-Control", "no-store").setBody("FGHIJ"));
    }
    server.start();
    URL url = server.url("/").url();
    HttpURLConnection connection = openConnection(url);
    assertEquals(expectedResponseCode, connection.getResponseCode());
    // Exhaust the content stream.
    readAscii(connection);
    CacheResponse cached = cache.get(url.toURI(), "GET", null);
    if (shouldPut) {
        assertNotNull(Integer.toString(responseCode), cached);
    } else {
        assertNull(Integer.toString(responseCode), cached);
    }
    // tearDown() isn't sufficient; this test starts multiple servers
    server.shutdown();
}
Also used : MockResponse(okhttp3.mockwebserver.MockResponse) CacheResponse(java.net.CacheResponse) SecureCacheResponse(java.net.SecureCacheResponse) HttpURLConnection(java.net.HttpURLConnection) MockWebServer(okhttp3.mockwebserver.MockWebServer) URL(java.net.URL)

Example 3 with Challenge

use of okhttp3.Challenge in project okhttp by square.

the class CacheTest method assertCached.

private void assertCached(boolean shouldPut, int responseCode) throws Exception {
    int expectedResponseCode = responseCode;
    server = new MockWebServer();
    MockResponse mockResponse = new MockResponse().addHeader("Last-Modified: " + formatDate(-1, TimeUnit.HOURS)).addHeader("Expires: " + formatDate(1, TimeUnit.HOURS)).setResponseCode(responseCode).setBody("ABCDE").addHeader("WWW-Authenticate: challenge");
    if (responseCode == HttpURLConnection.HTTP_PROXY_AUTH) {
        mockResponse.addHeader("Proxy-Authenticate: Basic realm=\"protected area\"");
    } else if (responseCode == HttpURLConnection.HTTP_UNAUTHORIZED) {
        mockResponse.addHeader("WWW-Authenticate: Basic realm=\"protected area\"");
    } else if (responseCode == HttpURLConnection.HTTP_NO_CONTENT || responseCode == HttpURLConnection.HTTP_RESET) {
        // We forbid bodies for 204 and 205.
        mockResponse.setBody("");
    }
    server.enqueue(mockResponse);
    if (responseCode == HttpURLConnection.HTTP_CLIENT_TIMEOUT) {
        // 408's are a bit of an outlier because we may repeat the request if we encounter this
        // response code. In this scenario, there are 2 responses: the initial 408 and then the 200
        // because of the retry. We just want to ensure the initial 408 isn't cached.
        expectedResponseCode = 200;
        server.enqueue(new MockResponse().setHeader("Cache-Control", "no-store").setBody("FGHIJ"));
    }
    server.start();
    Request request = new Request.Builder().url(server.url("/")).build();
    Response response = client.newCall(request).execute();
    assertEquals(expectedResponseCode, response.code());
    // Exhaust the content stream.
    response.body().string();
    Response cached = cache.get(request);
    if (shouldPut) {
        assertNotNull(Integer.toString(responseCode), cached);
        cached.body().close();
    } else {
        assertNull(Integer.toString(responseCode), cached);
    }
    // tearDown() isn't sufficient; this test starts multiple servers
    server.shutdown();
}
Also used : MockResponse(okhttp3.mockwebserver.MockResponse) MockResponse(okhttp3.mockwebserver.MockResponse) MockWebServer(okhttp3.mockwebserver.MockWebServer) RecordedRequest(okhttp3.mockwebserver.RecordedRequest)

Example 4 with Challenge

use of okhttp3.Challenge 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 5 with Challenge

use of okhttp3.Challenge in project okhttp by square.

the class URLConnectionTest method customBasicAuthenticator.

@Test
public void customBasicAuthenticator() throws Exception {
    MockResponse pleaseAuthenticate = new MockResponse().setResponseCode(401).addHeader("WWW-Authenticate: Basic realm=\"protected area\"").setBody("Please authenticate.");
    server.enqueue(pleaseAuthenticate);
    server.enqueue(new MockResponse().setBody("A"));
    String credential = Credentials.basic("jesse", "peanutbutter");
    RecordingOkAuthenticator authenticator = new RecordingOkAuthenticator(credential);
    urlFactory.setClient(urlFactory.client().newBuilder().authenticator(authenticator).build());
    assertContent("A", urlFactory.open(server.url("/private").url()));
    assertNull(server.takeRequest().getHeader("Authorization"));
    assertEquals(credential, server.takeRequest().getHeader("Authorization"));
    assertEquals(Proxy.NO_PROXY, authenticator.onlyProxy());
    Response response = authenticator.onlyResponse();
    assertEquals("/private", response.request().url().url().getPath());
    assertEquals(Arrays.asList(new Challenge("Basic", "protected area")), response.challenges());
}
Also used : MockResponse(okhttp3.mockwebserver.MockResponse) MockResponse(okhttp3.mockwebserver.MockResponse) RecordingOkAuthenticator(okhttp3.internal.RecordingOkAuthenticator) Test(org.junit.Test)

Aggregations

MockResponse (okhttp3.mockwebserver.MockResponse)7 Test (org.junit.Test)7 Request (okhttp3.Request)6 Challenge (okhttp3.Challenge)5 IOException (java.io.IOException)4 HashMap (java.util.HashMap)4 Authenticator (okhttp3.Authenticator)4 Response (okhttp3.Response)4 HttpURLConnection (java.net.HttpURLConnection)3 URL (java.net.URL)3 Map (java.util.Map)3 HttpUrl (okhttp3.HttpUrl)3 Route (okhttp3.Route)3 RecordingOkAuthenticator (okhttp3.internal.RecordingOkAuthenticator)3 HttpHeaders (okhttp3.internal.http.HttpHeaders)3 MockWebServer (okhttp3.mockwebserver.MockWebServer)3 RecordedRequest (okhttp3.mockwebserver.RecordedRequest)3 ArrayList (java.util.ArrayList)2 Matcher (java.util.regex.Matcher)2 Headers (okhttp3.Headers)2