Search in sources :

Example 11 with Challenge

use of okhttp3.Challenge in project okhttp by square.

the class HeadersTest method testDigestChallenges.

/** See https://github.com/square/okhttp/issues/2780. */
@Test
public void testDigestChallenges() {
    // Strict RFC 2617 header.
    Headers headers = new Headers.Builder().add("WWW-Authenticate", "Digest realm=\"myrealm\", nonce=\"fjalskdflwejrlaskdfjlaskdjflaks" + "jdflkasdf\", qop=\"auth\", stale=\"FALSE\"").build();
    List<Challenge> challenges = HttpHeaders.parseChallenges(headers, "WWW-Authenticate");
    assertEquals(1, challenges.size());
    assertEquals("Digest", challenges.get(0).scheme());
    assertEquals("myrealm", challenges.get(0).realm());
    // Not strict RFC 2617 header.
    headers = new Headers.Builder().add("WWW-Authenticate", "Digest qop=\"auth\", realm=\"myrealm\", nonce=\"fjalskdflwejrlask" + "dfjlaskdjflaksjdflkasdf\", stale=\"FALSE\"").build();
    challenges = HttpHeaders.parseChallenges(headers, "WWW-Authenticate");
    assertEquals(1, challenges.size());
    assertEquals("Digest", challenges.get(0).scheme());
    assertEquals("myrealm", challenges.get(0).realm());
    // Not strict RFC 2617 header #2.
    headers = new Headers.Builder().add("WWW-Authenticate", "Digest qop=\"auth\", nonce=\"fjalskdflwejrlaskdfjlaskdjflaksjdflk" + "asdf\", realm=\"myrealm\", stale=\"FALSE\"").build();
    challenges = HttpHeaders.parseChallenges(headers, "WWW-Authenticate");
    assertEquals(1, challenges.size());
    assertEquals("Digest", challenges.get(0).scheme());
    assertEquals("myrealm", challenges.get(0).realm());
    // Wrong header.
    headers = new Headers.Builder().add("WWW-Authenticate", "Digest qop=\"auth\", underrealm=\"myrealm\", nonce=\"fjalskdflwej" + "rlaskdfjlaskdjflaksjdflkasdf\", stale=\"FALSE\"").build();
    challenges = HttpHeaders.parseChallenges(headers, "WWW-Authenticate");
    assertEquals(0, challenges.size());
    // Not strict RFC 2617 header with some spaces.
    headers = new Headers.Builder().add("WWW-Authenticate", "Digest qop=\"auth\",    realm=\"myrealm\", nonce=\"fjalskdflwejrl" + "askdfjlaskdjflaksjdflkasdf\", stale=\"FALSE\"").build();
    challenges = HttpHeaders.parseChallenges(headers, "WWW-Authenticate");
    assertEquals(1, challenges.size());
    assertEquals("Digest", challenges.get(0).scheme());
    assertEquals("myrealm", challenges.get(0).realm());
    // Strict RFC 2617 header with some spaces.
    headers = new Headers.Builder().add("WWW-Authenticate", "Digest    realm=\"myrealm\", nonce=\"fjalskdflwejrlaskdfjlaskdjfl" + "aksjdflkasdf\", qop=\"auth\", stale=\"FALSE\"").build();
    challenges = HttpHeaders.parseChallenges(headers, "WWW-Authenticate");
    assertEquals(1, challenges.size());
    assertEquals("Digest", challenges.get(0).scheme());
    assertEquals("myrealm", challenges.get(0).realm());
    // Not strict RFC 2617 camelcased.
    headers = new Headers.Builder().add("WWW-Authenticate", "DiGeSt qop=\"auth\", rEaLm=\"myrealm\", nonce=\"fjalskdflwejrlask" + "dfjlaskdjflaksjdflkasdf\", stale=\"FALSE\"").build();
    challenges = HttpHeaders.parseChallenges(headers, "WWW-Authenticate");
    assertEquals(1, challenges.size());
    assertEquals("DiGeSt", challenges.get(0).scheme());
    assertEquals("myrealm", challenges.get(0).realm());
    // Strict RFC 2617 camelcased.
    headers = new Headers.Builder().add("WWW-Authenticate", "DIgEsT rEaLm=\"myrealm\", nonce=\"fjalskdflwejrlaskdfjlaskdjflaks" + "jdflkasdf\", qop=\"auth\", stale=\"FALSE\"").build();
    challenges = HttpHeaders.parseChallenges(headers, "WWW-Authenticate");
    assertEquals(1, challenges.size());
    assertEquals("DIgEsT", challenges.get(0).scheme());
    assertEquals("myrealm", challenges.get(0).realm());
    // Unquoted.
    headers = new Headers.Builder().add("WWW-Authenticate", "Digest realm=myrealm").build();
    challenges = HttpHeaders.parseChallenges(headers, "WWW-Authenticate");
    assertEquals(0, challenges.size());
    // Scheme only.
    headers = new Headers.Builder().add("WWW-Authenticate", "Digest").build();
    challenges = HttpHeaders.parseChallenges(headers, "WWW-Authenticate");
    assertEquals(0, challenges.size());
}
Also used : HttpHeaders(okhttp3.internal.http.HttpHeaders) Test(org.junit.Test)

Example 12 with Challenge

use of okhttp3.Challenge in project okhttp by square.

the class URLConnectionTest method unauthorizedResponseHandling.

/**
   * We've had a bug where we forget the HTTP response when we see response code 401. This causes a
   * new HTTP request to be issued for every call into the URLConnection.
   */
@Test
public void unauthorizedResponseHandling() throws IOException {
    MockResponse response = new MockResponse().addHeader("WWW-Authenticate: challenge").setResponseCode(// UNAUTHORIZED
    401).setBody("Unauthorized");
    server.enqueue(response);
    server.enqueue(response);
    server.enqueue(response);
    URL url = server.url("/").url();
    HttpURLConnection conn = urlFactory.open(url);
    assertEquals(401, conn.getResponseCode());
    assertEquals(401, conn.getResponseCode());
    assertEquals(401, conn.getResponseCode());
    assertEquals(1, server.getRequestCount());
    conn.getErrorStream().close();
}
Also used : MockResponse(okhttp3.mockwebserver.MockResponse) HttpURLConnection(java.net.HttpURLConnection) OkHttpURLConnection(okhttp3.internal.huc.OkHttpURLConnection) URL(java.net.URL) Test(org.junit.Test)

Example 13 with Challenge

use of okhttp3.Challenge in project okhttp by square.

the class RealConnection method connectTunnel.

/**
   * Does all the work to build an HTTPS connection over a proxy tunnel. The catch here is that a
   * proxy server can issue an auth challenge and then close the connection.
   */
private void connectTunnel(int connectTimeout, int readTimeout, int writeTimeout) throws IOException {
    Request tunnelRequest = createTunnelRequest();
    HttpUrl url = tunnelRequest.url();
    int attemptedConnections = 0;
    int maxAttempts = 21;
    while (true) {
        if (++attemptedConnections > maxAttempts) {
            throw new ProtocolException("Too many tunnel connections attempted: " + maxAttempts);
        }
        connectSocket(connectTimeout, readTimeout);
        tunnelRequest = createTunnel(readTimeout, writeTimeout, tunnelRequest, url);
        // Tunnel successfully created.
        if (tunnelRequest == null)
            break;
        // The proxy decided to close the connection after an auth challenge. We need to create a new
        // connection, but this time with the auth credentials.
        closeQuietly(rawSocket);
        rawSocket = null;
        sink = null;
        source = null;
    }
}
Also used : ProtocolException(java.net.ProtocolException) Request(okhttp3.Request) HttpUrl(okhttp3.HttpUrl)

Example 14 with Challenge

use of okhttp3.Challenge in project okhttp by square.

the class HttpHeaders method parseChallenges.

/**
   * Parse RFC 2617 challenges, also wrong ordered ones.
   * This API is only interested in the scheme name and realm.
   */
public static List<Challenge> parseChallenges(Headers responseHeaders, String challengeHeader) {
    // auth-scheme = token
    // auth-param  = token "=" ( token | quoted-string )
    // challenge   = auth-scheme 1*SP 1#auth-param
    // realm       = "realm" "=" realm-value
    // realm-value = quoted-string
    List<Challenge> challenges = new ArrayList<>();
    List<String> authenticationHeaders = responseHeaders.values(challengeHeader);
    for (String header : authenticationHeaders) {
        int index = header.indexOf(' ');
        if (index == -1)
            continue;
        Matcher matcher = PARAMETER.matcher(header);
        for (int i = index; matcher.find(i); i = matcher.end()) {
            if (header.regionMatches(true, matcher.start(1), "realm", 0, 5)) {
                String scheme = header.substring(0, index);
                String realm = matcher.group(3);
                if (realm != null) {
                    challenges.add(new Challenge(scheme, realm));
                    break;
                }
            }
        }
    }
    return challenges;
}
Also used : Matcher(java.util.regex.Matcher) ArrayList(java.util.ArrayList) Challenge(okhttp3.Challenge)

Example 15 with Challenge

use of okhttp3.Challenge in project mobile-sdk-android by meniga.

the class MenigaChallengesConverter method responseBodyConverter.

@Override
public Converter<ResponseBody, ?> responseBodyConverter(Type type, Annotation[] annotations, Retrofit retrofit) {
    Type typeOfChallenge = new TypeToken<MenigaChallenge>() {
    }.getType();
    Type typeOfChallenges = new TypeToken<List<MenigaChallenge>>() {
    }.getType();
    if (typeOfChallenge.equals(type)) {
        return new Converter<ResponseBody, MenigaChallenge>() {

            @Override
            public MenigaChallenge convert(ResponseBody resBody) throws IOException {
                return factory.getMenigaChallengeItem(getAsObject(resBody.byteStream()));
            }
        };
    } else if (typeOfChallenges.equals(type)) {
        return new Converter<ResponseBody, Object>() {

            @Override
            public Object convert(ResponseBody resBody) throws IOException {
                JsonArray arr = getAsArray(resBody.byteStream());
                List<MenigaChallenge> challenges = new ArrayList<>();
                for (JsonElement element : arr) {
                    MenigaChallenge challenge = factory.getMenigaChallengeItem((JsonObject) element);
                    if (challenge.getTitle().equals("GlobalSpendingMeterMarker")) {
                        challenge.setType(ChallengeType.METER);
                    }
                    challenges.add(challenge);
                }
                return challenges;
            }
        };
    }
    return null;
}
Also used : JsonObject(com.google.gson.JsonObject) IOException(java.io.IOException) ResponseBody(okhttp3.ResponseBody) JsonArray(com.google.gson.JsonArray) ChallengeType(com.meniga.sdk.models.challenges.enums.ChallengeType) Type(java.lang.reflect.Type) JsonElement(com.google.gson.JsonElement) Converter(retrofit2.Converter) ArrayList(java.util.ArrayList) List(java.util.List) JsonObject(com.google.gson.JsonObject) MenigaChallenge(com.meniga.sdk.models.challenges.MenigaChallenge)

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