Example usage for com.squareup.okhttp Authenticator Authenticator

List of usage examples for com.squareup.okhttp Authenticator Authenticator

Introduction

In this page you can find the example usage for com.squareup.okhttp Authenticator Authenticator.

Prototype

Authenticator

Source Link

Usage

From source file:com.anony.okhttp.sample.Authenticate.java

License:Apache License

public void run() throws Exception {
    client.setAuthenticator(new Authenticator() {
        @Override// w w w .  ja v a2 s  .c  om
        public Request authenticate(Proxy proxy, Response response) {
            System.out.println("Authenticating for response: " + response);
            System.out.println("Challenges: " + response.challenges());
            String credential = Credentials.basic("jesse", "password1");
            return response.request().newBuilder().header("Authorization", credential).build();
        }

        @Override
        public Request authenticateProxy(Proxy proxy, Response response) {
            return null; // Null indicates no attempt to authenticate.
        }
    });

    Request request = new Request.Builder().url("http://publicobject.com/secrets/hellosecret.txt").build();

    Response response = client.newCall(request).execute();
    if (!response.isSuccessful())
        throw new IOException("Unexpected code " + response);

    System.out.println(response.body().string());
}

From source file:com.cuddlesoft.norilib.clients.Danbooru.java

/**
 * Create a new Danbooru 1.x client with authentication.
 *
 * @param name     Human-readable service name.
 * @param endpoint URL to the HTTP API Endpoint - the server implementing the API.
 * @param username Username used for authentication.
 * @param apiKey   API key used for authentication.
 *//*w w  w .  ja  v  a 2  s  .c  o m*/
public Danbooru(String name, String endpoint, String username, final String apiKey) {
    this.name = name;
    this.apiEndpoint = endpoint;
    this.username = username;
    this.apiKey = apiKey;

    // Enable HTTP Basic Authentication.
    okHttpClient.setAuthenticator(new Authenticator() {
        @Override
        public Request authenticate(Proxy proxy, Response response) throws IOException {
            final String credential = Base64.encodeToString(
                    String.format("%s:%s", Danbooru.this.username, Danbooru.this.apiKey).getBytes(),
                    Base64.DEFAULT);
            return response.request().newBuilder().header("Authorization", credential).build();
        }

        @Override
        public Request authenticateProxy(Proxy proxy, Response response) throws IOException {
            return null;
        }
    });
}

From source file:com.cuddlesoft.norilib.clients.DanbooruLegacy.java

/**
 * Create a new Danbooru 1.x client with authentication.
 *
 * @param endpoint URL to the HTTP API Endpoint - the server implementing the API.
 * @param username Username used for authentication.
 * @param password Password used for authentication.
 *//* w w  w .j  a  va 2  s  . c  o  m*/
public DanbooruLegacy(String name, String endpoint, String username, String password) {
    this.name = name;
    this.apiEndpoint = endpoint;
    this.username = username;
    this.password = password;

    // Enable HTTP basic authentication.
    okHttpClient.setAuthenticator(new Authenticator() {
        @Override
        public Request authenticate(Proxy proxy, Response response) throws IOException {
            final String credential = Credentials.basic(DanbooruLegacy.this.username,
                    DanbooruLegacy.this.password);
            return response.request().newBuilder().header("Authorization", credential).build();
        }

        @Override
        public Request authenticateProxy(Proxy proxy, Response response) throws IOException {
            return null;
        }
    });
}

From source file:com.digi.wva.internal.HttpClientTest.java

License:Mozilla Public License

/**
 * Just for code coverage over the request/response logging and basic "is it working" test.
 * This will cover the code branches where the prior request was NOT a redirect.
 *///from   w w w  .ja va 2  s . co  m
public void testAuthChallenge() {
    dut.setLoggingEnabled(true);

    // First send an auth challenge
    server.enqueue(
            new MockResponse().addHeader("WWW-Authenticate", "Basic realm=\"foo\"").setResponseCode(401));
    // Then send an OK response
    server.enqueue(new MockResponse().setResponseCode(200).setBody("{}"));

    // Need to set up an Authenticator to handle the challenge though. But as was mentioned above,
    // this test is purely to exercise the code for a) coverage and b) assurance that it doesn't
    // error out in this case.
    dut.getUnderlyingClient().setAuthenticator(new Authenticator() {
        @Override
        public Request authenticate(Proxy proxy, Response response) throws IOException {
            // See https://github.com/square/okhttp/wiki/Recipes, "Handling authentication"
            String credentials = com.squareup.okhttp.Credentials.basic("user", "pass");
            return response.request().newBuilder().header("Authorization", credentials).build();
        }

        @Override
        public Request authenticateProxy(Proxy proxy, Response response) throws IOException {
            return null;
        }
    });
    dut.get("some_url", callback);

    PassFailHttpCallback.RecordedResponse r = callback.await();
    assertTrue(r.success);
    assertNull(r.error);
}

From source file:com.github.radium226.github.maven.AssetWagon.java

License:Apache License

@Override
public void doConnect(Optional<AuthenticationInfo> authenticationInfo) throws ConnectionException {
    try {//from ww w.j a v a2 s .  c o  m
        // GitHub Authentication
        GitHubBuilder gitHubBuilder = new GitHubBuilder();
        if (authenticationInfo.isPresent()) {
            String login = authenticationInfo.get().getUserName();
            String password = authenticationInfo.get().getPassword();
            if (password.startsWith("oauth2_token:")) {
                gitHubBuilder = gitHubBuilder.withOAuthToken(password.substring("oauth2_otken:".length()));
            } else {
                gitHubBuilder = gitHubBuilder.withPassword(login, password);
            }
        }

        // Proxy Authentication
        okHttpClient = new OkHttpClient();
        ProxyInfo proxyInfo = getProxyInfoByType("http");
        if (proxyInfo != null) {
            okHttpClient.setProxy(ProxyInfos.asProxy(proxyInfo));
            final String userName = proxyInfo.getUserName();
            final String password = proxyInfo.getPassword();
            if (userName != null && password != null) {
                okHttpClient.setAuthenticator(new Authenticator() {

                    @Override
                    public Request authenticateProxy(Proxy proxy, Response response) {
                        return response.request();
                    }

                    @Override
                    public Request authenticate(Proxy proxy, Response response) throws IOException {
                        String credentials = Credentials.basic(userName, password);
                        return response.request().newBuilder().header("Proxy-Authorization", credentials)
                                .build();
                    }

                });
            }
        }
        gitHub = gitHubBuilder.withConnector(new OkHttpConnector(new OkUrlFactory(okHttpClient))).build();

        this.gitHubService = GitHubService.forGitHub(gitHub).withHttpClient(okHttpClient);

        GHMyself myself = gitHub.getMyself();
        LOGGER.info("Connected as {}", myself.getName());
    } catch (IOException e) {
        throw new ConnectionException("Unable to connect to GitHub", e);
    }

}

From source file:es.bsc.vmmclient.rest.VmmRestClient.java

License:Open Source License

public VmmRestClient(String url, long timeout, final String username, final String password) {
    if (url.startsWith("https://")) {
        // TODO: add the option to accept only Trusted HTTPS connections
        okHttpClient = getUnsafeOkHttpClient();
    } else {//from   w w w. j  a  v a2s.co m
        okHttpClient = new OkHttpClient();
    }
    // Define our own okHttpClient to increase the timeout
    okHttpClient.setReadTimeout(timeout, TimeUnit.SECONDS);

    if (username != null && password != null) {
        okHttpClient.setAuthenticator(new Authenticator() {
            @Override
            public Request authenticate(Proxy proxy, Response response) throws IOException {
                String credential = Credentials.basic(username, password);
                return response.request().newBuilder().header("Authorization", credential).build();
            }

            @Override
            public Request authenticateProxy(Proxy proxy, Response response) throws IOException {
                return null;
            }
        });
    }

    RestAdapter restAdapter = new RestAdapter.Builder().setEndpoint(url).setClient(new OkClient(okHttpClient))
            .build();
    service = restAdapter.create(VmmService.class);
}

From source file:io.fabric8.devops.connector.DevOpsConnector.java

License:Apache License

protected void createGerritRepo(String repoName, String gerritUser, String gerritPwd,
        String gerritGitInitialCommit, String gerritGitRepoDescription) throws Exception {

    // lets add defaults if not env vars
    final String username = Strings.isNullOrBlank(gerritUser) ? "admin" : gerritUser;
    final String password = Strings.isNullOrBlank(gerritPwd) ? "secret" : gerritPwd;

    log.info("A Gerrit git repo will be created for this name : " + repoName);

    String gerritAddress = KubernetesHelper.getServiceURL(kubernetes, ServiceNames.GERRIT, namespace, "http",
            true);//  w  w  w. ja va 2  s. c om
    log.info("Found gerrit address: " + gerritAddress + " for namespace: " + namespace
            + " on Kubernetes address: " + kubernetes.getMasterUrl());

    if (Strings.isNullOrBlank(gerritAddress)) {
        throw new Exception("No address for service " + ServiceNames.GERRIT + " in namespace: " + namespace
                + " on Kubernetes address: " + kubernetes.getMasterUrl());
    }

    String GERRIT_URL = gerritAddress + "/a/projects/" + repoName;

    OkHttpClient client = new OkHttpClient();
    if (isNotNullOrEmpty(gerritUser) && isNotNullOrEmpty(gerritPwd)) {
        client.setAuthenticator(new Authenticator() {
            @Override
            public Request authenticate(Proxy proxy, Response response) throws IOException {
                List<Challenge> challenges = response.challenges();
                Request request = response.request();
                for (int i = 0, size = challenges.size(); i < size; i++) {
                    Challenge challenge = challenges.get(i);
                    if (!"Basic".equalsIgnoreCase(challenge.getScheme()))
                        continue;

                    String credential = Credentials.basic(username, password);
                    return request.newBuilder().header("Authorization", credential).build();
                }
                return null;
            }

            @Override
            public Request authenticateProxy(Proxy proxy, Response response) throws IOException {
                return null;
            }
        });
    }

    System.out.println("Requesting : " + GERRIT_URL);

    try {
        CreateRepositoryDTO createRepoDTO = new CreateRepositoryDTO();
        createRepoDTO.setDescription(gerritGitRepoDescription);
        createRepoDTO.setName(repoName);
        createRepoDTO.setCreate_empty_commit(Boolean.valueOf(gerritGitInitialCommit));

        RequestBody body = RequestBody.create(JSON, MAPPER.writeValueAsString(createRepoDTO));
        Request request = new Request.Builder().post(body).url(GERRIT_URL).build();
        Response response = client.newCall(request).execute();
        System.out.println("responseBody : " + response.body().string());

    } catch (Throwable t) {
        throw new RuntimeException(t);
    } finally {
        if (client != null && client.getConnectionPool() != null) {
            client.getConnectionPool().evictAll();
        }
    }
}

From source file:io.fabric8.docker.client.utils.HttpClientUtils.java

License:Apache License

public static OkHttpClient createHttpClient(final Config config) {
    try {//from   w w w . j ava 2  s.c o m
        OkHttpClient httpClient = new OkHttpClient();

        httpClient.setConnectionPool(ConnectionPool.getDefault());
        // Follow any redirects
        httpClient.setFollowRedirects(true);
        httpClient.setFollowSslRedirects(true);

        if (config.isTrustCerts()) {
            httpClient.setHostnameVerifier(new HostnameVerifier() {
                @Override
                public boolean verify(String s, SSLSession sslSession) {
                    return true;
                }
            });
        }

        if (usesUnixSocket(config)) {
            URL masterURL = new URL(config.getDockerUrl().replaceFirst(UNIX_SCHEME, FILE_SCHEME));
            httpClient.setSocketFactory(new UnixSocketFactory(masterURL.getFile()));
            config.setDockerUrl(UNIX_FAKE_URL);
        }

        TrustManager[] trustManagers = SSLUtils.trustManagers(config);
        KeyManager[] keyManagers = SSLUtils.keyManagers(config);

        if (keyManagers != null || trustManagers != null || config.isTrustCerts()) {
            try {
                SSLContext sslContext = SSLUtils.sslContext(keyManagers, trustManagers, config.isTrustCerts());
                httpClient.setSslSocketFactory(sslContext.getSocketFactory());
            } catch (GeneralSecurityException e) {
                throw new AssertionError(); // The system has no TLS. Just give up.
            }
        }

        if (isNotNullOrEmpty(config.getUsername()) && isNotNullOrEmpty(config.getPassword())) {
            httpClient.setAuthenticator(new Authenticator() {

                @Override
                public Request authenticate(Proxy proxy, Response response) throws IOException {
                    List<Challenge> challenges = response.challenges();
                    Request request = response.request();
                    HttpUrl url = request.httpUrl();
                    for (int i = 0, size = challenges.size(); i < size; i++) {
                        Challenge challenge = challenges.get(i);
                        if (!"Basic".equalsIgnoreCase(challenge.getScheme()))
                            continue;

                        String credential = Credentials.basic(config.getUsername(), config.getPassword());
                        return request.newBuilder().header("Authorization", credential).build();
                    }
                    return null;
                }

                @Override
                public Request authenticateProxy(Proxy proxy, Response response) throws IOException {
                    return null;
                }
            });
        } else if (config.getOauthToken() != null) {
            httpClient.interceptors().add(new Interceptor() {
                @Override
                public Response intercept(Chain chain) throws IOException {
                    Request authReq = chain.request().newBuilder()
                            .addHeader("Authorization", "Bearer " + config.getOauthToken()).build();
                    return chain.proceed(authReq);
                }
            });
        }

        Logger reqLogger = LoggerFactory.getLogger(HttpLoggingInterceptor.class);
        if (reqLogger.isTraceEnabled()) {
            HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor();
            loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
            httpClient.networkInterceptors().add(loggingInterceptor);
        }

        if (config.getConnectionTimeout() > 0) {
            httpClient.setConnectTimeout(config.getConnectionTimeout(), TimeUnit.MILLISECONDS);
        }

        if (config.getRequestTimeout() > 0) {
            httpClient.setReadTimeout(config.getRequestTimeout(), TimeUnit.MILLISECONDS);
        }

        // Only check proxy if it's a full URL with protocol
        if (config.getDockerUrl().toLowerCase().startsWith(Config.HTTP_PROTOCOL_PREFIX)
                || config.getDockerUrl().startsWith(Config.HTTPS_PROTOCOL_PREFIX)) {
            try {
                URL proxyUrl = getProxyUrl(config);
                if (proxyUrl != null) {
                    httpClient.setProxy(new Proxy(Proxy.Type.HTTP,
                            new InetSocketAddress(proxyUrl.getHost(), proxyUrl.getPort())));
                }
            } catch (MalformedURLException e) {
                throw new DockerClientException("Invalid proxy server configuration", e);
            }
        }

        return httpClient;
    } catch (Exception e) {
        throw DockerClientException.launderThrowable(e);
    }
}

From source file:io.fabric8.kubernetes.client.utils.HttpClientUtils.java

License:Apache License

public static OkHttpClient createHttpClient(final Config config) {
    try {/*from   www.  j a v a2 s  .c  o  m*/
        OkHttpClient httpClient = new OkHttpClient();

        // Follow any redirects
        httpClient.setFollowRedirects(true);
        httpClient.setFollowSslRedirects(true);

        if (config.isTrustCerts()) {
            httpClient.setHostnameVerifier(new HostnameVerifier() {
                @Override
                public boolean verify(String s, SSLSession sslSession) {
                    return true;
                }
            });
        }

        TrustManager[] trustManagers = SSLUtils.trustManagers(config);
        KeyManager[] keyManagers = SSLUtils.keyManagers(config);

        if (keyManagers != null || trustManagers != null || config.isTrustCerts()) {
            try {
                SSLContext sslContext = SSLUtils.sslContext(keyManagers, trustManagers, config.isTrustCerts());
                httpClient.setSslSocketFactory(sslContext.getSocketFactory());
            } catch (GeneralSecurityException e) {
                throw new AssertionError(); // The system has no TLS. Just give up.
            }
        }

        if (isNotNullOrEmpty(config.getUsername()) && isNotNullOrEmpty(config.getPassword())) {
            httpClient.setAuthenticator(new Authenticator() {

                @Override
                public Request authenticate(Proxy proxy, Response response) throws IOException {
                    List<Challenge> challenges = response.challenges();
                    Request request = response.request();
                    HttpUrl url = request.httpUrl();
                    for (int i = 0, size = challenges.size(); i < size; i++) {
                        Challenge challenge = challenges.get(i);
                        if (!"Basic".equalsIgnoreCase(challenge.getScheme()))
                            continue;

                        String credential = Credentials.basic(config.getUsername(), config.getPassword());
                        return request.newBuilder().header("Authorization", credential).build();
                    }
                    return null;
                }

                @Override
                public Request authenticateProxy(Proxy proxy, Response response) throws IOException {
                    return null;
                }
            });
        } else if (config.getOauthToken() != null) {
            httpClient.interceptors().add(new Interceptor() {
                @Override
                public Response intercept(Chain chain) throws IOException {
                    Request authReq = chain.request().newBuilder()
                            .addHeader("Authorization", "Bearer " + config.getOauthToken()).build();
                    return chain.proceed(authReq);
                }
            });
        }

        Logger reqLogger = LoggerFactory.getLogger(HttpLoggingInterceptor.class);
        if (reqLogger.isTraceEnabled()) {
            HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor();
            loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
            httpClient.networkInterceptors().add(loggingInterceptor);
        }

        if (config.getConnectionTimeout() > 0) {
            httpClient.setConnectTimeout(config.getConnectionTimeout(), TimeUnit.MILLISECONDS);
        }

        if (config.getRequestTimeout() > 0) {
            httpClient.setReadTimeout(config.getRequestTimeout(), TimeUnit.MILLISECONDS);
        }

        // Only check proxy if it's a full URL with protocol
        if (config.getMasterUrl().toLowerCase().startsWith(Config.HTTP_PROTOCOL_PREFIX)
                || config.getMasterUrl().startsWith(Config.HTTPS_PROTOCOL_PREFIX)) {
            try {
                URL proxyUrl = getProxyUrl(config);
                if (proxyUrl != null) {
                    httpClient.setProxy(new Proxy(Proxy.Type.HTTP,
                            new InetSocketAddress(proxyUrl.getHost(), proxyUrl.getPort())));
                }
            } catch (MalformedURLException e) {
                throw new KubernetesClientException("Invalid proxy server configuration", e);
            }
        }

        if (config.getUserAgent() != null && !config.getUserAgent().isEmpty()) {
            httpClient.networkInterceptors().add(new Interceptor() {
                @Override
                public Response intercept(Chain chain) throws IOException {
                    Request agent = chain.request().newBuilder().header("User-Agent", config.getUserAgent())
                            .build();
                    return chain.proceed(agent);
                }
            });
        }

        return httpClient;
    } catch (Exception e) {
        throw KubernetesClientException.launderThrowable(e);
    }
}

From source file:io.morea.handy.android.SendLogTask.java

License:Apache License

public SendLogTask(final Context context, final EventReporterConfiguration configuration) {
    // Don't make Context a WeakReference, otherwise the reference could get collected before the task is actually
    // run and the task should be executed in any case. There's also no risk to create a memory leak here because
    // the task will be thrown away afterwards anyway.
    this.context = context;
    this.configuration = configuration;

    client = new OkHttpClient();
    client.setConnectTimeout(configuration.getHttpTimeout(), TimeUnit.MILLISECONDS);
    client.setWriteTimeout(configuration.getHttpTimeout(), TimeUnit.MILLISECONDS);
    client.setReadTimeout(configuration.getHttpTimeout(), TimeUnit.MILLISECONDS);
    client.setAuthenticator(new Authenticator() {
        @Override//from ww w.j av  a 2 s.c o m
        public Request authenticate(Proxy proxy, Response response) {
            String credential = Credentials.basic(configuration.getProbeId(), configuration.getAccessKey());
            return response.request().newBuilder().header("Authorization", credential).build();
        }

        @Override
        public Request authenticateProxy(Proxy proxy, Response response) {
            return null;
        }
    });

    GsonBuilder gsonBuilder = new GsonBuilder();
    gsonBuilder.registerTypeAdapter(Date.class, new DateSerializer());
    this.gson = gsonBuilder.create();
}