Search in sources :

Example 6 with Challenge

use of okhttp3.Challenge in project okhttp by square.

the class CallTest method proxyAuthenticateOnConnect.

/** Respond to a proxy authorization challenge. */
@Test
public void proxyAuthenticateOnConnect() throws Exception {
    server.useHttps(sslClient.socketFactory, true);
    server.enqueue(new MockResponse().setResponseCode(407).addHeader("Proxy-Authenticate: Basic realm=\"localhost\""));
    server.enqueue(new MockResponse().setSocketPolicy(SocketPolicy.UPGRADE_TO_SSL_AT_END).clearHeaders());
    server.enqueue(new MockResponse().setBody("response body"));
    client = client.newBuilder().sslSocketFactory(sslClient.socketFactory, sslClient.trustManager).proxy(server.toProxyAddress()).proxyAuthenticator(new RecordingOkAuthenticator("password")).hostnameVerifier(new RecordingHostnameVerifier()).build();
    Request request = new Request.Builder().url("https://android.com/foo").build();
    Response response = client.newCall(request).execute();
    assertEquals("response body", response.body().string());
    RecordedRequest connect1 = server.takeRequest();
    assertEquals("CONNECT android.com:443 HTTP/1.1", connect1.getRequestLine());
    assertNull(connect1.getHeader("Proxy-Authorization"));
    RecordedRequest connect2 = server.takeRequest();
    assertEquals("CONNECT android.com:443 HTTP/1.1", connect2.getRequestLine());
    assertEquals("password", connect2.getHeader("Proxy-Authorization"));
    RecordedRequest get = server.takeRequest();
    assertEquals("GET /foo HTTP/1.1", get.getRequestLine());
    assertNull(get.getHeader("Proxy-Authorization"));
}
Also used : MockResponse(okhttp3.mockwebserver.MockResponse) RecordedRequest(okhttp3.mockwebserver.RecordedRequest) MockResponse(okhttp3.mockwebserver.MockResponse) RecordingOkAuthenticator(okhttp3.internal.RecordingOkAuthenticator) RecordedRequest(okhttp3.mockwebserver.RecordedRequest) Test(org.junit.Test)

Example 7 with Challenge

use of okhttp3.Challenge in project okhttp by square.

the class UrlConnectionCacheTest method assertCached.

private void assertCached(boolean shouldPut, int responseCode) throws Exception {
    int expectedResponseCode = responseCode;
    server = new MockWebServer();
    MockResponse response = 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) {
        response.addHeader("Proxy-Authenticate: Basic realm=\"protected area\"");
    } else if (responseCode == HttpURLConnection.HTTP_UNAUTHORIZED) {
        response.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.
        response.setBody("");
    }
    server.enqueue(response);
    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().addHeader("Cache-Control", "no-store").setBody("FGHIJ"));
    }
    server.start();
    URL url = server.url("/").url();
    HttpURLConnection conn = urlFactory.open(url);
    assertEquals(expectedResponseCode, conn.getResponseCode());
    // exhaust the content stream
    readAscii(conn);
    Response cached = cache.get(new Request.Builder().url(url).build());
    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) HttpURLConnection(java.net.HttpURLConnection) MockWebServer(okhttp3.mockwebserver.MockWebServer) RecordedRequest(okhttp3.mockwebserver.RecordedRequest) URL(java.net.URL)

Example 8 with Challenge

use of okhttp3.Challenge in project couchbase-lite-android by couchbase.

the class CBLWebSocket method setupAuthenticator.

private Authenticator setupAuthenticator() {
    if (options != null && options.containsKey(kC4ReplicatorOptionAuthentication)) {
        Map<String, Object> auth = (Map<String, Object>) options.get(kC4ReplicatorOptionAuthentication);
        if (auth != null) {
            final String username = (String) auth.get(kC4ReplicatorAuthUserName);
            final String password = (String) auth.get(kC4ReplicatorAuthPassword);
            if (username != null && password != null) {
                return new Authenticator() {

                    @Override
                    public Request authenticate(Route route, Response response) throws IOException {
                        // http://www.ietf.org/rfc/rfc2617.txt
                        Log.v(TAG, "Authenticating for response: " + response);
                        // If failed 3 times, give up.
                        if (responseCount(response) >= 3)
                            return null;
                        List<Challenge> challenges = response.challenges();
                        Log.v(TAG, "Challenges: " + challenges);
                        if (challenges != null) {
                            for (Challenge challenge : challenges) {
                                if (challenge.scheme().equals("Basic")) {
                                    String credential = Credentials.basic(username, password);
                                    return response.request().newBuilder().header("Authorization", credential).build();
                                }
                            // NOTE: Not implemented Digest authentication
                            // https://github.com/rburgst/okhttp-digest
                            // else if(challenge.scheme().equals("Digest")){
                            // }
                            }
                        }
                        return null;
                    }
                };
            }
        }
    }
    return null;
}
Also used : Response(okhttp3.Response) ByteString(okio.ByteString) HashMap(java.util.HashMap) Map(java.util.Map) Authenticator(okhttp3.Authenticator) Route(okhttp3.Route) Challenge(okhttp3.Challenge)

Example 9 with Challenge

use of okhttp3.Challenge in project autorest-clientruntime-for-java by Azure.

the class AzureTokenCredentials method applyCredentialsFilter.

@Override
public void applyCredentialsFilter(OkHttpClient.Builder clientBuilder) {
    clientBuilder.interceptors().add(new AzureTokenCredentialsInterceptor(this));
    clientBuilder.authenticator(new Authenticator() {

        @Override
        public Request authenticate(Route route, Response response) throws IOException {
            String authenticateHeader = response.header("WWW-Authenticate");
            if (authenticateHeader != null && !authenticateHeader.isEmpty()) {
                Pattern pattern = Pattern.compile("resource=\"([a-zA-Z0-9.:/-_]+)\"");
                Matcher matcher = pattern.matcher(authenticateHeader);
                if (matcher.find()) {
                    String resource = matcher.group(1);
                    return response.request().newBuilder().header("Authorization", "Bearer " + getToken(resource)).build();
                }
            }
            // Otherwise cannot satisfy the challenge
            return null;
        }
    });
}
Also used : Response(okhttp3.Response) Pattern(java.util.regex.Pattern) Matcher(java.util.regex.Matcher) Request(okhttp3.Request) IOException(java.io.IOException) Authenticator(okhttp3.Authenticator) Route(okhttp3.Route)

Example 10 with Challenge

use of okhttp3.Challenge in project NewPipe by TeamNewPipe.

the class Downloader method getBody.

private ResponseBody getBody(String siteUrl, Map<String, String> customProperties) throws IOException, ReCaptchaException {
    final Request.Builder requestBuilder = new Request.Builder().method("GET", null).url(siteUrl).addHeader("User-Agent", USER_AGENT);
    for (Map.Entry<String, String> header : customProperties.entrySet()) {
        requestBuilder.addHeader(header.getKey(), header.getValue());
    }
    if (!TextUtils.isEmpty(mCookies)) {
        requestBuilder.addHeader("Cookie", mCookies);
    }
    final Request request = requestBuilder.build();
    final Response response = client.newCall(request).execute();
    final ResponseBody body = response.body();
    if (response.code() == 429) {
        throw new ReCaptchaException("reCaptcha Challenge requested");
    }
    if (body == null) {
        response.close();
        return null;
    }
    return body;
}
Also used : Response(okhttp3.Response) Request(okhttp3.Request) HashMap(java.util.HashMap) Map(java.util.Map) ResponseBody(okhttp3.ResponseBody) ReCaptchaException(org.schabi.newpipe.extractor.exceptions.ReCaptchaException)

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