Example usage for org.apache.http.auth UsernamePasswordCredentials UsernamePasswordCredentials

List of usage examples for org.apache.http.auth UsernamePasswordCredentials UsernamePasswordCredentials

Introduction

In this page you can find the example usage for org.apache.http.auth UsernamePasswordCredentials UsernamePasswordCredentials.

Prototype

public UsernamePasswordCredentials(final String userName, final String password) 

Source Link

Document

The constructor with the username and password arguments.

Usage

From source file:com.liferay.mobile.sdk.auth.DigestAuthentication.java

@Override
public Request authenticate(Proxy proxy, Response response) throws IOException {

    Request request = response.request();

    Builder builder = request.newBuilder();

    try {//ww w  .j av  a 2  s  .co  m
        BasicHeader authenticateHeader = new BasicHeader(Headers.WWW_AUTHENTICATE,
                response.header(Headers.WWW_AUTHENTICATE));

        DigestScheme scheme = new DigestScheme();

        scheme.processChallenge(authenticateHeader);

        BasicHttpRequest basicHttpRequest = new BasicHttpRequest(request.method(), request.uri().getPath());

        UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(username, password);

        String authorizationHeader = scheme.authenticate(credentials, basicHttpRequest).getValue();

        builder.addHeader(Headers.AUTHORIZATION, authorizationHeader);
    } catch (Exception e) {
        throw new IOException(e);
    }

    return builder.build();
}

From source file:org.etk.common.net.ETKHttpClient.java

public HttpEntity execute(String targetURL) throws ClientProtocolException, IOException {
    HttpHost targetHost = new HttpHost("127.0.0.1", 8080, "http");

    httpClient.getCredentialsProvider().setCredentials(
            new AuthScope(targetHost.getHostName(), targetHost.getPort()),
            new UsernamePasswordCredentials("demo", "gtn"));

    // Create AuthCache instance
    AuthCache authCache = new BasicAuthCache();
    // Generate BASIC scheme object and add it to the local auth cache
    BasicScheme basicAuth = new BasicScheme();
    authCache.put(targetHost, basicAuth);

    // Add AuthCache to the execution context
    BasicHttpContext localcontext = new BasicHttpContext();
    localcontext.setAttribute(ClientContext.AUTH_CACHE, authCache);

    HttpGet httpget = new HttpGet(targetURL);
    Header header = new BasicHeader("Content-Type", "application/json");
    httpget.setHeader(header);//from  w  w  w .j  a v a  2s.  com
    HttpResponse response = httpClient.execute(targetHost, httpget, localcontext);
    DumpHttpResponse.dumpHeader(response);
    HttpEntity entity = response.getEntity();
    if (entity != null) {
        entity = new BufferedHttpEntity(entity);
    }
    EntityUtils.consume(entity);

    return entity;
}

From source file:com.cisco.cta.taxii.adapter.httpclient.CredentialsProviderFactory.java

private void addProxyCredentials(CredentialsProvider credsProvider) {
    if (proxySettings.getUrl() == null) {
        return;/*from  w  ww .  j  a v  a 2s.  c o m*/
    }
    if (proxySettings.getAuthenticationType() == null) {
        throw new IllegalStateException("Both proxy url and proxy authentication type have to be specified.");
    }

    ProxyAuthenticationType authType = proxySettings.getAuthenticationType();

    URL proxyUrl = proxySettings.getUrl();
    HttpHost proxyHost = new HttpHost(proxyUrl.getHost(), proxyUrl.getPort(), proxyUrl.getProtocol());

    Credentials credentials;
    switch (authType) {
    case NONE:
        break;

    case BASIC:
        credentials = new UsernamePasswordCredentials(proxySettings.getUsername(), proxySettings.getPassword());
        credsProvider.setCredentials(new AuthScope(proxyHost.getHostName(), proxyHost.getPort()), credentials);
        break;

    case NTLM:
        credentials = new NTCredentials(proxySettings.getUsername(), proxySettings.getPassword(),
                proxySettings.getWorkstation(), proxySettings.getDomain());
        credsProvider.setCredentials(new AuthScope(proxyHost.getHostName(), proxyHost.getPort()), credentials);
        break;

    default:
        throw new IllegalStateException("Unsupported authentication type: " + authType);
    }
}

From source file:com.squeezecontrol.download.MusicDownloadService.java

public MusicDownloadService(MusicBrowser musicBrowser, String baseUrl, String username, String password) {
    this.mMusicBrowser = musicBrowser;
    this.mBaseUrl = baseUrl;
    this.mSongFolder = Environment.getExternalStorageDirectory() + "/Music/";

    mClient = new DefaultHttpClient();
    if (username != null && !"".equals(username)) {
        Credentials defaultcreds = new UsernamePasswordCredentials("dag", "test");
        mClient.getCredentialsProvider().setCredentials(AuthScope.ANY, defaultcreds);
    }//from w ww.  j  av  a2  s  . c om
}

From source file:org.sonatype.nexus.ant.staging.deploy.ZapperImpl.java

@Override
public void deployDirectory(final ZapperRequest zapperRequest) throws IOException {
    try {/*from   w ww. j a va2  s. c  o  m*/
        HttpHost proxyServer = null;
        BasicCredentialsProvider credentialsProvider = null;
        if (!StringUtils.isBlank(zapperRequest.getProxyProtocol())) {
            proxyServer = new HttpHost(zapperRequest.getProxyHost(), zapperRequest.getProxyPort(),
                    zapperRequest.getProxyProtocol());

            if (!StringUtils.isBlank(zapperRequest.getProxyUsername())) {
                UsernamePasswordCredentials proxyCredentials = new UsernamePasswordCredentials(
                        zapperRequest.getProxyUsername(), zapperRequest.getProxyPassword());

                credentialsProvider = new BasicCredentialsProvider();
                credentialsProvider.setCredentials(new AuthScope(proxyServer.getHostName(),
                        proxyServer.getPort(), AuthScope.ANY_REALM, proxyServer.getSchemeName()),
                        proxyCredentials);
            }
        }

        if (!StringUtils.isBlank(zapperRequest.getRemoteUsername())) {
            UsernamePasswordCredentials remoteCredentials = new UsernamePasswordCredentials(
                    zapperRequest.getRemoteUsername(), zapperRequest.getRemotePassword());

            if (credentialsProvider == null) {
                credentialsProvider = new BasicCredentialsProvider();
            }

            credentialsProvider.setCredentials(AuthScope.ANY, remoteCredentials);
        }

        final Parameters parameters = ParametersBuilder.defaults().build();
        final Hc4ClientBuilder clientBuilder = new Hc4ClientBuilder(parameters, zapperRequest.getRemoteUrl());
        if (credentialsProvider != null) {
            clientBuilder.withPreemptiveRealm(credentialsProvider);
        }
        if (proxyServer != null) {
            clientBuilder.withProxy(proxyServer);
        }
        final Client client = clientBuilder.build();
        final IOSourceListable deployables = new DirectoryIOSource(zapperRequest.getStageRepository());

        try {
            client.upload(deployables);
        } finally {
            client.close();
        }
    } catch (IOException e) {
        throw e;
    } catch (Exception e) {
        throw new IOException("Unable to deploy!", e);
    }
}

From source file:org.springframework.cloud.dataflow.shell.command.support.HttpClientUtils.java

/**
 * Ensures that the passed-in {@link RestTemplate} is using the Apache HTTP Client. If the optional {@code username} AND
 * {@code password} are not empty, then a {@link BasicCredentialsProvider} will be added to the {@link CloseableHttpClient}.
 *
 * Furthermore, you can set the underlying {@link SSLContext} of the {@link HttpClient} allowing you to accept self-signed
 * certificates.//www.j ava 2  s .com
 *
 * @param restTemplate Must not be null
 * @param username Can be null
 * @param password Can be null
 * @param skipSslValidation Use with caution! If true certificate warnings will be ignored.
 */
public static void prepareRestTemplate(RestTemplate restTemplate, URI host, String username, String password,
        boolean skipSslValidation) {

    Assert.notNull(restTemplate, "The provided RestTemplate must not be null.");

    final HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();

    if (StringUtils.hasText(username) && StringUtils.hasText(password)) {
        final BasicCredentialsProvider credentialsProvider = new BasicCredentialsProvider();
        credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(username, password));
        httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider);
    }

    if (skipSslValidation) {
        httpClientBuilder.setSSLContext(HttpClientUtils.buildCertificateIgnoringSslContext());
        httpClientBuilder.setSSLHostnameVerifier(new NoopHostnameVerifier());
    }

    final CloseableHttpClient httpClient = httpClientBuilder.build();
    final HttpHost targetHost = new HttpHost(host.getHost(), host.getPort(), host.getScheme());

    final HttpComponentsClientHttpRequestFactory requestFactory = new PreemptiveBasicAuthHttpComponentsClientHttpRequestFactory(
            httpClient, targetHost);
    restTemplate.setRequestFactory(requestFactory);
}

From source file:org.overlord.security.eval.webapp1.services.JaxrsService.java

/**
 * @return/*from  w  w  w  .j a v  a2  s . co  m*/
 */
private ClientExecutor getBasicAuthExecutor() {
    String password = PASS + "||" + this.context.getRemoteUser();
    Credentials credentials = new UsernamePasswordCredentials(USER, password);
    DefaultHttpClient httpClient = new DefaultHttpClient();
    httpClient.getCredentialsProvider().setCredentials(AuthScope.ANY, credentials);
    ClientExecutor clientExecutor = new ApacheHttpClient4Executor(httpClient);
    return clientExecutor;
}

From source file:org.apache.edgent.connectors.http.HttpClients.java

/**
 * Method to create a basic authentication HTTP client.
 * The functions {@code user} and {@code password} are called
 * when this method is invoked to obtain the user and password
 * and runtime.//from w  ww  .j a va  2  s .  c o  m
 * 
 * @param user Function that provides user for authentication
 * @param password  Function that provides password for authentication
 * @return HTTP client with basic authentication.
 * 
 * @see HttpStreams
 */
public static CloseableHttpClient basic(Supplier<String> user, Supplier<String> password) {

    CredentialsProvider credsProvider = new BasicCredentialsProvider();
    credsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(user.get(), password.get()));

    return HttpClientBuilder.create().setDefaultCredentialsProvider(credsProvider).build();
}

From source file:org.mycontroller.standalone.restclient.RestFactory.java

public T createAPI(URI uri, String userName, String password) {
    CloseableHttpClient httpclient = HttpClientBuilder.create().build();
    HttpHost targetHost = new HttpHost(uri.getHost(), uri.getPort());
    CredentialsProvider credsProvider = new BasicCredentialsProvider();
    credsProvider.setCredentials(new AuthScope(targetHost.getHostName(), targetHost.getPort()),
            new UsernamePasswordCredentials(userName, password));
    // Create AuthCache instance
    AuthCache authCache = new BasicAuthCache();
    // Generate BASIC scheme object and add it to the local auth cache
    BasicScheme basicAuth = new BasicScheme();
    authCache.put(targetHost, basicAuth);
    // Add AuthCache to the execution context
    HttpClientContext context = HttpClientContext.create();
    context.setCredentialsProvider(credsProvider);
    context.setAuthCache(authCache);/*w  w  w.j  a va  2s. c  om*/
    ApacheHttpClient4Engine engine = new ApacheHttpClient4Engine(httpclient, context);

    ResteasyClient client = new ResteasyClientBuilder().httpEngine(engine).build();
    client.register(JacksonJaxbJsonProvider.class);
    client.register(RequestLogger.class);
    client.register(ResponseLogger.class);
    ProxyBuilder<T> proxyBuilder = client.target(uri).proxyBuilder(proxyClazz);
    return proxyBuilder.build();
}

From source file:org.syncope.core.rest.UserRequestTestITCase.java

@Test
public void selfRead() {
    PreemptiveAuthHttpRequestFactory requestFactory = ((PreemptiveAuthHttpRequestFactory) restTemplate
            .getRequestFactory());//from   w  ww.j av a2s. c  om
    ((DefaultHttpClient) requestFactory.getHttpClient()).getCredentialsProvider().setCredentials(
            requestFactory.getAuthScope(), new UsernamePasswordCredentials("user1", "password"));

    SyncopeClientException exception = null;
    try {
        restTemplate.getForObject(BASE_URL + "user/read/{userId}.json", UserTO.class, 1);
        fail();
    } catch (SyncopeClientCompositeErrorException e) {
        exception = e.getException(SyncopeClientExceptionType.UnauthorizedRole);
    }
    assertNotNull(exception);

    UserTO userTO = restTemplate.getForObject(BASE_URL + "user/request/read/self", UserTO.class);
    assertEquals("user1", userTO.getUsername());
}