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:io.getlime.push.service.fcm.FcmClient.java

/**
 * Set information about proxy./*from  ww  w . j ava2 s .co  m*/
 * @param host Proxy host URL.
 * @param port Proxy port.
 * @param username Proxy username, use 'null' for proxy without authentication.
 * @param password Proxy user password, ignored in case username is 'null'
 */
public void setProxy(String host, int port, String username, String password) {

    HttpAsyncClientBuilder clientBuilder = HttpAsyncClientBuilder.create();
    clientBuilder.useSystemProperties();
    clientBuilder.setProxy(new HttpHost(host, port));

    if (username != null) {
        CredentialsProvider credsProvider = new BasicCredentialsProvider();
        UsernamePasswordCredentials user = new UsernamePasswordCredentials(username, password);
        credsProvider.setCredentials(new AuthScope(host, port), user);
        clientBuilder.setDefaultCredentialsProvider(credsProvider);
        clientBuilder.setProxyAuthenticationStrategy(new ProxyAuthenticationStrategy());
    }

    CloseableHttpAsyncClient client = clientBuilder.build();

    HttpComponentsAsyncClientHttpRequestFactory factory = new HttpComponentsAsyncClientHttpRequestFactory();
    factory.setAsyncClient(client);

    restTemplate.setAsyncRequestFactory(factory);
}

From source file:org.xwiki.extension.repository.xwiki.internal.httpclient.DefaultHttpClientFactory.java

@Override
public HttpClient createClient(String user, String password) {
    DefaultHttpClient httpClient = new DefaultHttpClient();

    httpClient.getParams().setParameter(CoreProtocolPNames.USER_AGENT, this.configuration.getUserAgent());
    httpClient.getParams().setIntParameter(CoreConnectionPNames.SO_TIMEOUT, 60000);
    httpClient.getParams().setIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 10000);

    // Setup proxy
    ProxySelectorRoutePlanner routePlanner = new ProxySelectorRoutePlanner(
            httpClient.getConnectionManager().getSchemeRegistry(), ProxySelector.getDefault());
    httpClient.setRoutePlanner(routePlanner);

    // Setup authentication
    if (user != null) {
        httpClient.getCredentialsProvider().setCredentials(AuthScope.ANY,
                new UsernamePasswordCredentials(user, password));
    }/*from  w ww . j a v a  2  s . c o m*/

    return httpClient;
}

From source file:org.apache.nifi.processors.gcp.ProxyAwareTransportFactory.java

@Override
public HttpTransport create() {

    if (proxyConfig == null) {
        return DEFAULT_TRANSPORT;
    }/* w  w w  .  j  ava  2  s  . com*/

    final Proxy proxy = proxyConfig.createProxy();

    if (Proxy.Type.HTTP.equals(proxy.type()) && proxyConfig.hasCredential()) {
        // If it requires authentication via username and password, use ApacheHttpTransport
        final String host = proxyConfig.getProxyServerHost();
        final int port = proxyConfig.getProxyServerPort();
        final HttpHost proxyHost = new HttpHost(host, port);

        final DefaultHttpClient httpClient = new DefaultHttpClient();
        ConnRouteParams.setDefaultProxy(httpClient.getParams(), proxyHost);

        if (proxyConfig.hasCredential()) {
            final AuthScope proxyAuthScope = new AuthScope(host, port);
            final UsernamePasswordCredentials proxyCredential = new UsernamePasswordCredentials(
                    proxyConfig.getProxyUserName(), proxyConfig.getProxyUserPassword());
            final BasicCredentialsProvider credentialsProvider = new BasicCredentialsProvider();
            credentialsProvider.setCredentials(proxyAuthScope, proxyCredential);
            httpClient.setCredentialsProvider(credentialsProvider);
        }

        return new ApacheHttpTransport(httpClient);

    }

    return new NetHttpTransport.Builder().setProxy(proxy).build();
}

From source file:brooklyn.rest.resources.ServerResourceIntegrationTest.java

/**
 * [sam] Other tests rely on brooklyn.properties not containing security properties so ..
 * I think the best way to test this is to set a security provider, then reload properties
 * and check no authentication is required.
 * //from ww  w.  j  a  v a 2s .  c  o m
 * [aled] Changing this test so doesn't rely on brooklyn.properties having no security
 * provider (that can lead to failures locally when running just this test). Asserts 
 */
@Test(groups = "Integration")
public void testSecurityProviderUpdatesWhenPropertiesReloaded() {
    BrooklynProperties brooklynProperties = BrooklynProperties.Factory.newEmpty();
    brooklynProperties.put("brooklyn.webconsole.security.users", "admin");
    brooklynProperties.put("brooklyn.webconsole.security.user.admin.password", "mypassword");
    UsernamePasswordCredentials defaultCredential = new UsernamePasswordCredentials("admin", "mypassword");

    ManagementContext mgmt = new LocalManagementContext(brooklynProperties);

    try {
        Server server = useServerForTest(BrooklynRestApiLauncher.launcher().managementContext(mgmt)
                .withoutJsgui().securityProvider(TestSecurityProvider.class).start());
        String baseUri = getBaseUri(server);

        HttpToolResponse response;
        final URI uri = URI.create(getBaseUri() + "/v1/server/properties/reload");
        final Map<String, String> args = Collections.emptyMap();

        // Unauthorised when no credentials, and when default credentials.
        response = HttpTool.httpPost(httpClientBuilder().uri(baseUri).build(), uri, args, args);
        assertEquals(response.getResponseCode(), HttpStatus.SC_UNAUTHORIZED);

        response = HttpTool.httpPost(httpClientBuilder().uri(baseUri).credentials(defaultCredential).build(),
                uri, args, args);
        assertEquals(response.getResponseCode(), HttpStatus.SC_UNAUTHORIZED);

        // Accepts TestSecurityProvider credentials, and we reload.
        response = HttpTool.httpPost(
                httpClientBuilder().uri(baseUri).credentials(TestSecurityProvider.CREDENTIAL).build(), uri,
                args, args);
        HttpTestUtils.assertHealthyStatusCode(response.getResponseCode());

        // Has no gone back to credentials from brooklynProperties; TestSecurityProvider credentials no longer work
        response = HttpTool.httpPost(httpClientBuilder().uri(baseUri).credentials(defaultCredential).build(),
                uri, args, args);
        HttpTestUtils.assertHealthyStatusCode(response.getResponseCode());

        response = HttpTool.httpPost(
                httpClientBuilder().uri(baseUri).credentials(TestSecurityProvider.CREDENTIAL).build(), uri,
                args, args);
        assertEquals(response.getResponseCode(), HttpStatus.SC_UNAUTHORIZED);

    } finally {
        ((ManagementContextInternal) mgmt).terminate();
    }
}

From source file:org.commonjava.maven.galley.transport.htcli.internal.TLLocationCredentialsProvider.java

public synchronized void bind(final Collection<HttpLocation> locations) {
    if (locations != null) {
        final Map<AuthScope, Credentials> creds = new HashMap<AuthScope, Credentials>();
        final Map<AuthScope, HttpLocation> repos = new HashMap<AuthScope, HttpLocation>();
        for (final HttpLocation location : locations) {
            final AuthScope as = new AuthScope(location.getHost(), location.getPort());
            //                logger.info( "Storing repository def: {} under authscope: {}:{}", repository.getName(),
            //                             repository.getHost(), repository.getPort() );

            //TODO: Seems like multiple repos with same host/port could easily cause confusion if they're not configured the same way later on...
            repos.put(as, location);/*www  . ja  v a2 s.  c o m*/

            if (location.getUser() != null) {
                creds.put(as, new UsernamePasswordCredentials(location.getUser(),
                        passwordManager.getPassword(new PasswordEntry(location, PasswordEntry.USER_PASSWORD))));
            }

            if (location.getProxyHost() != null && location.getProxyUser() != null) {
                creds.put(new AuthScope(location.getProxyHost(), location.getProxyPort()),
                        new UsernamePasswordCredentials(location.getProxyUser(), passwordManager
                                .getPassword(new PasswordEntry(location, PasswordEntry.PROXY_PASSWORD))));
            }
        }

        this.credentials.set(creds);
        this.repositories.set(repos);
    }
}

From source file:kuona.jenkins.analyser.JenkinsClient.java

/**
 * Create an authenticated Jenkins HTTP client
 *
 * @param uri      Location of the jenkins server (ex. http://localhost:8080)
 * @param username Username to use when connecting
 * @param password Password or auth token to use when connecting
 *///from  w w  w. j a  va2 s  . co  m
public JenkinsClient(Project project, URI uri, String username, String password) {
    this(project, uri);
    if (isNotBlank(username)) {
        CredentialsProvider provider = client.getCredentialsProvider();
        AuthScope scope = new AuthScope(uri.getHost(), uri.getPort(), "realm");
        UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(username, password);
        provider.setCredentials(scope, credentials);

        localContext = new BasicHttpContext();
        localContext.setAttribute("preemptive-auth", new BasicScheme());
        client.addRequestInterceptor(new PreemptiveAuth(), 0);
    }
}

From source file:org.springframework.cloud.dataflow.rest.util.HttpClientConfigurer.java

public HttpClientConfigurer basicAuthCredentials(String username, String password) {
    final CredentialsProvider credentialsProvider = this.getOrInitializeCredentialsProvider();
    credentialsProvider.setCredentials(new AuthScope(this.targetHost),
            new UsernamePasswordCredentials(username, password));
    httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider);
    useBasicAuth = true;//  w  w  w.j a  va  2  s.  c om
    return this;
}

From source file:de.fraunhofer.iosb.ilt.stc.auth.AuthBasic.java

@Override
public void setAuth(SensorThingsService service) {
    try {/*from w  w  w  .  j  av a2 s .  co m*/
        CredentialsProvider credsProvider = new BasicCredentialsProvider();
        URL url = service.getEndpoint().toURL();
        credsProvider.setCredentials(new AuthScope(url.getHost(), url.getPort()),
                new UsernamePasswordCredentials(editorUsername.getValue(), editorPassword.getValue()));
        CloseableHttpClient httpclient = HttpClients.custom().setDefaultCredentialsProvider(credsProvider)
                .build();
        service.setClient(httpclient);
    } catch (MalformedURLException ex) {
        LOGGER.error("Failed to initialise basic auth.", ex);
    }
}

From source file:com.urswolfer.intellij.plugin.gerrit.rest.ProxyHttpClientBuilderExtension.java

@Override
public CredentialsProvider extendCredentialProvider(HttpClientBuilder httpClientBuilder,
        CredentialsProvider credentialsProvider, GerritAuthData authData) {
    HttpConfigurable proxySettings = HttpConfigurable.getInstance();
    IdeaWideProxySelector ideaWideProxySelector = new IdeaWideProxySelector(proxySettings);

    // This will always return at least one proxy, which can be the "NO_PROXY" instance.
    List<Proxy> proxies = ideaWideProxySelector.select(URI.create(authData.getHost()));

    // Find the first real proxy with an address type we support.
    for (Proxy proxy : proxies) {
        SocketAddress socketAddress = proxy.address();

        if (HttpConfigurable.isRealProxy(proxy) && socketAddress instanceof InetSocketAddress) {
            InetSocketAddress address = (InetSocketAddress) socketAddress;
            HttpHost proxyHttpHost = new HttpHost(address.getHostName(), address.getPort());
            httpClientBuilder.setProxy(proxyHttpHost);

            // Here we use the single username/password that we got from IDEA's settings. It feels kinda strange
            // to use these credential but it's probably what the user expects.
            if (proxySettings.PROXY_AUTHENTICATION) {
                AuthScope authScope = new AuthScope(proxySettings.PROXY_HOST, proxySettings.PROXY_PORT);
                UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(
                        proxySettings.PROXY_LOGIN, proxySettings.getPlainProxyPassword());
                credentialsProvider.setCredentials(authScope, credentials);
                break;
            }//from www. j  a v  a 2 s  .  co  m
        }
    }
    return credentialsProvider;
}

From source file:org.sonar.updatecenter.server.HttpDownloader.java

File downloadFile(URI fileURI, File toFile, String login, String password) {
    LOG.info("Download " + fileURI + " in " + toFile);
    DefaultHttpClient client = new DefaultHttpClient();
    try {/*from   w w  w  .  j a  v a 2  s.  c  o m*/
        if (StringUtils.isNotBlank(login)) {
            client.getCredentialsProvider().setCredentials(new AuthScope(fileURI.getHost(), fileURI.getPort()),
                    new UsernamePasswordCredentials(login, password));
        }
        HttpGet httpget = new HttpGet(fileURI);
        byte[] data = client.execute(httpget, new ByteResponseHandler());
        if (data != null) {
            FileUtils.writeByteArrayToFile(toFile, data);
        }

    } catch (Exception e) {
        LOG.error("Fail to download " + fileURI + " to " + toFile, e);
        FileUtils.deleteQuietly(toFile);

    } finally {
        client.getConnectionManager().shutdown();
    }
    return toFile;
}