Search in sources :

Example 51 with Credentials

use of okhttp3.Credentials in project okhttp by square.

the class CallTest method noProactiveProxyAuthorization.

/**
   * Confirm that we don't send the Proxy-Authorization header from the request to the proxy server.
   * We used to have that behavior but it is problematic because unrelated requests end up sharing
   * credentials. Worse, that approach leaks proxy credentials to the origin server.
   */
@Test
public void noProactiveProxyAuthorization() throws Exception {
    server.useHttps(sslClient.socketFactory, true);
    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()).hostnameVerifier(new RecordingHostnameVerifier()).build();
    Request request = new Request.Builder().url("https://android.com/foo").header("Proxy-Authorization", "password").build();
    Response response = client.newCall(request).execute();
    assertEquals("response body", response.body().string());
    RecordedRequest connect = server.takeRequest();
    assertNull(connect.getHeader("Proxy-Authorization"));
    RecordedRequest get = server.takeRequest();
    assertEquals("password", get.getHeader("Proxy-Authorization"));
}
Also used : MockResponse(okhttp3.mockwebserver.MockResponse) RecordedRequest(okhttp3.mockwebserver.RecordedRequest) MockResponse(okhttp3.mockwebserver.MockResponse) RecordedRequest(okhttp3.mockwebserver.RecordedRequest) Test(org.junit.Test)

Example 52 with Credentials

use of okhttp3.Credentials 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 53 with Credentials

use of okhttp3.Credentials in project zipkin by openzipkin.

the class AWSSignatureVersion4 method sign.

Request sign(Request input) throws IOException {
    AWSCredentials credentials = checkNotNull(this.credentials.get(), "awsCredentials");
    String timestamp = iso8601.get().format(new Date());
    String yyyyMMdd = timestamp.substring(0, 8);
    String credentialScope = format("%s/%s/%s/%s", yyyyMMdd, region, service, "aws4_request");
    Request.Builder builder = input.newBuilder();
    builder.header(HOST, input.url().host());
    builder.header(X_AMZ_DATE, timestamp);
    if (credentials.sessionToken != null) {
        builder.header(X_AMZ_SECURITY_TOKEN, credentials.sessionToken);
    }
    Buffer canonicalString = canonicalString(builder.build());
    String signedHeaders = credentials.sessionToken == null ? HOST_DATE : HOST_DATE_TOKEN;
    Buffer toSign = toSign(timestamp, credentialScope, canonicalString);
    // TODO: this key is invalid when the secret key or the date change. both are very infrequent
    ByteString signatureKey = signatureKey(credentials.secretKey, yyyyMMdd);
    String signature = toSign.readByteString().hmacSha256(signatureKey).hex();
    String authorization = new StringBuilder().append("AWS4-HMAC-SHA256 Credential=").append(credentials.accessKey).append('/').append(credentialScope).append(", SignedHeaders=").append(signedHeaders).append(", Signature=").append(signature).toString();
    return builder.header("authorization", authorization).build();
}
Also used : Buffer(okio.Buffer) ByteString(okio.ByteString) Request(okhttp3.Request) ByteString(okio.ByteString) Date(java.util.Date)

Example 54 with Credentials

use of okhttp3.Credentials in project AntennaPod by AntennaPod.

the class GpodnetService method executeRequestWithAuthentication.

private String executeRequestWithAuthentication(Request.Builder requestB, String username, String password) throws GpodnetServiceException {
    if (requestB == null || username == null || password == null) {
        throw new IllegalArgumentException("request and credentials must not be null");
    }
    Request request = requestB.header("User-Agent", ClientConfig.USER_AGENT).build();
    String result = null;
    ResponseBody body = null;
    try {
        String credential = Credentials.basic(username, password);
        Request authRequest = request.newBuilder().header("Authorization", credential).build();
        Response response = httpClient.newCall(authRequest).execute();
        checkStatusCode(response);
        body = response.body();
        result = getStringFromResponseBody(body);
    } catch (Exception e) {
        e.printStackTrace();
        throw new GpodnetServiceException(e);
    } finally {
        if (body != null) {
            body.close();
        }
    }
    return result;
}
Also used : GpodnetEpisodeActionPostResponse(de.danoeh.antennapod.core.gpoddernet.model.GpodnetEpisodeActionPostResponse) Response(okhttp3.Response) GpodnetUploadChangesResponse(de.danoeh.antennapod.core.gpoddernet.model.GpodnetUploadChangesResponse) GpodnetEpisodeActionGetResponse(de.danoeh.antennapod.core.gpoddernet.model.GpodnetEpisodeActionGetResponse) Request(okhttp3.Request) URISyntaxException(java.net.URISyntaxException) JSONException(org.json.JSONException) MalformedURLException(java.net.MalformedURLException) IOException(java.io.IOException) ResponseBody(okhttp3.ResponseBody)

Example 55 with Credentials

use of okhttp3.Credentials in project sonarlint-core by SonarSource.

the class HttpConnectorTest method use_basic_authentication_with_null_password.

@Test
public void use_basic_authentication_with_null_password() throws Exception {
    answerHelloWorld();
    underTest = HttpConnector.newBuilder().url(serverUrl).credentials("theLogin", null).build();
    GetRequest request = new GetRequest("api/issues/search");
    underTest.call(request);
    RecordedRequest recordedRequest = server.takeRequest();
    assertThat(recordedRequest.getHeader("Authorization")).isEqualTo(basic("theLogin", ""));
}
Also used : RecordedRequest(okhttp3.mockwebserver.RecordedRequest) Test(org.junit.Test)

Aggregations

Request (okhttp3.Request)39 Response (okhttp3.Response)29 OkHttpClient (okhttp3.OkHttpClient)22 IOException (java.io.IOException)20 Test (org.junit.Test)16 HttpUrl (okhttp3.HttpUrl)10 RequestBody (okhttp3.RequestBody)9 RecordedRequest (okhttp3.mockwebserver.RecordedRequest)9 ResponseBody (okhttp3.ResponseBody)8 NonNull (androidx.annotation.NonNull)7 MockResponse (okhttp3.mockwebserver.MockResponse)7 BasicAuthenticator (com.burgstaller.okhttp.basic.BasicAuthenticator)6 CachingAuthenticator (com.burgstaller.okhttp.digest.CachingAuthenticator)6 Credentials (com.burgstaller.okhttp.digest.Credentials)6 DigestAuthenticator (com.burgstaller.okhttp.digest.DigestAuthenticator)6 Observable (rx.Observable)6 AuthenticationCacheInterceptor (com.burgstaller.okhttp.AuthenticationCacheInterceptor)5 CachingAuthenticatorDecorator (com.burgstaller.okhttp.CachingAuthenticatorDecorator)5 PokemonGo (com.pokegoapi.api.PokemonGo)5 PtcCredentialProvider (com.pokegoapi.auth.PtcCredentialProvider)5