Example usage for org.apache.http.impl.client BasicCredentialsProvider BasicCredentialsProvider

List of usage examples for org.apache.http.impl.client BasicCredentialsProvider BasicCredentialsProvider

Introduction

In this page you can find the example usage for org.apache.http.impl.client BasicCredentialsProvider BasicCredentialsProvider.

Prototype

public BasicCredentialsProvider() 

Source Link

Document

Default constructor.

Usage

From source file:majordodo.client.http.HTTPClientConnection.java

private HttpClientContext getContext() throws IOException {
    if (context == null) {
        BrokerAddress broker = getBroker();
        String scheme = broker.getProtocol();
        HttpHost targetHost = new HttpHost(broker.getAddress(), broker.getPort(), scheme);

        context = HttpClientContext.create();
        if (configuration.getUsername() != null && !configuration.getUsername().isEmpty()) {
            UsernamePasswordCredentials creds = new UsernamePasswordCredentials(configuration.getUsername(),
                    configuration.getPassword());
            CredentialsProvider credsProvider = new BasicCredentialsProvider();
            credsProvider.setCredentials(new AuthScope(targetHost.getHostName(), targetHost.getPort(),
                    AuthScope.ANY_REALM, AuthScope.ANY_SCHEME), creds);
            BasicAuthCache authCache = new BasicAuthCache();
            BasicScheme basicAuth = new BasicScheme();
            authCache.put(targetHost, basicAuth);
            context.setCredentialsProvider(credsProvider);
            context.setAuthCache(authCache);
        }//from   w w w  . j  av a2s  .  co  m

    }
    return context;
}

From source file:org.wildfly.test.integration.elytron.http.PasswordMechTestBase.java

@Test
public void testInvalidCredential() throws Exception {
    HttpGet request = new HttpGet(new URI(url.toExternalForm() + "role1"));
    UsernamePasswordCredentials credentials = new UsernamePasswordCredentials("user1", "password1wrong");

    CredentialsProvider credsProvider = new BasicCredentialsProvider();
    credsProvider.setCredentials(AuthScope.ANY, credentials);

    try (CloseableHttpClient httpClient = HttpClients.custom().setDefaultCredentialsProvider(credsProvider)
            .build()) {//from   w ww  . j ava2 s  .c o m
        try (CloseableHttpResponse response = httpClient.execute(request)) {
            int statusCode = response.getStatusLine().getStatusCode();
            assertEquals("Unexpected status code in HTTP response.", SC_UNAUTHORIZED, statusCode);
        }
    }
}

From source file:org.fcrepo.mint.HttpPidMinter.java

/**
 * Setup authentication in httpclient./*from   w ww .ja  v a2 s .  com*/
 * @return the setup of authentication
**/
protected HttpClient buildClient() {
    HttpClientBuilder builder = HttpClientBuilder.create().useSystemProperties()
            .setConnectionManager(connManager);
    if (!isBlank(username) && !isBlank(password)) {
        final URI uri = URI.create(url);
        final CredentialsProvider credsProvider = new BasicCredentialsProvider();
        credsProvider.setCredentials(new AuthScope(uri.getHost(), uri.getPort()),
                new UsernamePasswordCredentials(username, password));
        builder = builder.setDefaultCredentialsProvider(credsProvider);
    }
    return builder.build();
}

From source file:de.adorsys.oauth.loginmodule.HTTPAuthenticationLoginModule.java

private boolean authenticate(String username, String password) throws LoginException {
    HttpHost targetHost = new HttpHost(restEndpoint.getHost(), restEndpoint.getPort(),
            restEndpoint.getScheme());/*from  w  w  w  .ja va  2 s. co m*/
    CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
    credentialsProvider.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(Consts.UTF_8);
    authCache.put(targetHost, basicAuth);

    // Add AuthCache to the execution context
    HttpClientContext context = HttpClientContext.create();
    context.setCredentialsProvider(credentialsProvider);
    context.setAuthCache(authCache);

    HttpGet httpGet = new HttpGet(restEndpoint);

    CloseableHttpResponse userInfoResponse = null;
    try {
        userInfoResponse = HTTP_CLIENT.execute(httpGet, context);
        if (userInfoResponse.getStatusLine().getStatusCode() != 200) {
            LOG.error("Authentication failed for user {}, restEndpoint {} HTTP Status {}", username,
                    restEndpoint.toASCIIString(), userInfoResponse.getStatusLine());
            throw new LoginException("Authentication failed for user " + username + ", restEndpoint "
                    + restEndpoint.toASCIIString() + " HTTP Status " + userInfoResponse.getStatusLine());
        }
        String userInfoJson = readUserInfo(userInfoResponse);
        JSONObject userInfo = new JSONObject(userInfoJson);
        String principalId = userInfo.getString("principal");
        if (principalId == null) {
            LOG.error("could not read  field 'principal' for user {}. Response: {}", username, userInfoJson);
            throw new LoginException(
                    "could not read  field 'principal' for user " + username + ". Response: " + userInfoJson);
        }
        JSONArray roles = userInfo.getJSONArray("roles");

        populateSubject(principalId, roles);

        // we put them to shared stated that other login providers can also
        // authenticate
        sharedState.put("javax.security.auth.login.name", principalId);
        sharedState.put("javax.security.auth.login.password", password);
    } catch (IOException e) {
        throw new IllegalStateException("problem on http backend authentication", e);
    } finally {
        if (userInfoResponse != null) {
            try {
                userInfoResponse.close();
            } catch (IOException e) {
                ; // NOOP
            }
        }
    }
    return true;
}

From source file:de.vanita5.twittnuker.util.net.TwidereHttpClientImpl.java

public TwidereHttpClientImpl(final Context context, final HttpClientConfiguration conf) {
    this.conf = conf;
    final HttpClientBuilder clientBuilder = HttpClients.custom();
    final LayeredConnectionSocketFactory factory = TwidereSSLSocketFactory.getSocketFactory(context,
            conf.isSSLErrorIgnored());/*from w w  w  .j a v  a 2s.  c  o m*/
    clientBuilder.setSSLSocketFactory(factory);
    final RequestConfig.Builder requestConfigBuilder = RequestConfig.custom();
    requestConfigBuilder.setConnectionRequestTimeout(conf.getHttpConnectionTimeout());
    requestConfigBuilder.setConnectTimeout(conf.getHttpConnectionTimeout());
    requestConfigBuilder.setSocketTimeout(conf.getHttpReadTimeout());
    requestConfigBuilder.setRedirectsEnabled(false);
    clientBuilder.setDefaultRequestConfig(requestConfigBuilder.build());
    if (conf.isProxyConfigured()) {
        final HttpHost proxy = new HttpHost(conf.getHttpProxyHost(), conf.getHttpProxyPort());
        clientBuilder.setProxy(proxy);
        if (!TextUtils.isEmpty(conf.getHttpProxyUser())) {
            if (logger.isDebugEnabled()) {
                logger.debug("Proxy AuthUser: " + conf.getHttpProxyUser());
                logger.debug(
                        "Proxy AuthPassword: " + InternalStringUtil.maskString(conf.getHttpProxyPassword()));
            }
            final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
            credentialsProvider.setCredentials(new AuthScope(conf.getHttpProxyHost(), conf.getHttpProxyPort()),
                    new UsernamePasswordCredentials(conf.getHttpProxyUser(), conf.getHttpProxyPassword()));
            clientBuilder.setDefaultCredentialsProvider(credentialsProvider);
        }
    }
    client = clientBuilder.build();
}

From source file:org.nebula.framework.client.NebulaRestClient.java

private HttpClientContext createPreemptiveBasicAuthentication(String accessId, String password) {
    CredentialsProvider credsProvider = new BasicCredentialsProvider();
    credsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(accessId, password));

    AuthCache authCache = new BasicAuthCache();
    authCache.put(target, new BasicScheme());

    // Add AuthCache to the execution context
    HttpClientContext context = HttpClientContext.create();
    context.setCredentialsProvider(credsProvider);
    context.setAuthCache(authCache);/*www. j  a va 2  s .  co m*/

    return context;
}

From source file:org.jboss.as.test.integration.web.security.WebSecuritySimpleRoleMappingSecurityManagerTestCase.java

private void makeCall(String user, String pass, int expectedCode, String expectedOut) throws Exception {
    CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
    credentialsProvider.setCredentials(new AuthScope(url.getHost(), url.getPort()),
            new UsernamePasswordCredentials(user, pass));
    try (CloseableHttpClient httpclient = HttpClients.custom()
            .setDefaultCredentialsProvider(credentialsProvider).build()) {
        HttpGet httpget = new HttpGet(url.toExternalForm() + "rolemapping-secured/");
        HttpResponse response = httpclient.execute(httpget);
        HttpEntity entity = response.getEntity();
        StatusLine statusLine = response.getStatusLine();
        assertEquals(expectedCode, statusLine.getStatusCode());
        InputStream input = entity.getContent();
        assertEquals(expectedOut, new String(IOUtil.asByteArray(input)));
        input.close();//from www .j  a  v a 2 s .c  o m
    }
}

From source file:org.apache.manifoldcf.authorities.authorities.jira.JiraSession.java

/**
 * Constructor. Create a session.//from w  ww.ja va2 s .com
 */
public JiraSession(String clientId, String clientSecret, String protocol, String host, int port, String path,
        String proxyHost, int proxyPort, String proxyDomain, String proxyUsername, String proxyPassword)
        throws ManifoldCFException {
    this.host = new HttpHost(host, port, protocol);
    this.path = path;
    this.clientId = clientId;
    this.clientSecret = clientSecret;

    int socketTimeout = 900000;
    int connectionTimeout = 60000;

    javax.net.ssl.SSLSocketFactory httpsSocketFactory = KeystoreManagerFactory.getTrustingSecureSocketFactory();
    SSLConnectionSocketFactory myFactory = new SSLConnectionSocketFactory(
            new InterruptibleSocketFactory(httpsSocketFactory, connectionTimeout),
            SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);

    connectionManager = new PoolingHttpClientConnectionManager();

    CredentialsProvider credentialsProvider = new BasicCredentialsProvider();

    // If authentication needed, set that
    if (clientId != null) {
        credentialsProvider.setCredentials(AuthScope.ANY,
                new UsernamePasswordCredentials(clientId, clientSecret));
    }

    RequestConfig.Builder requestBuilder = RequestConfig.custom().setCircularRedirectsAllowed(true)
            .setSocketTimeout(socketTimeout).setStaleConnectionCheckEnabled(true).setExpectContinueEnabled(true)
            .setConnectTimeout(connectionTimeout).setConnectionRequestTimeout(socketTimeout);

    // If there's a proxy, set that too.
    if (proxyHost != null && proxyHost.length() > 0) {

        // Configure proxy authentication
        if (proxyUsername != null && proxyUsername.length() > 0) {
            if (proxyPassword == null)
                proxyPassword = "";
            if (proxyDomain == null)
                proxyDomain = "";

            credentialsProvider.setCredentials(new AuthScope(proxyHost, proxyPort),
                    new NTCredentials(proxyUsername, proxyPassword, currentHost, proxyDomain));
        }

        HttpHost proxy = new HttpHost(proxyHost, proxyPort);
        requestBuilder.setProxy(proxy);
    }

    httpClient = HttpClients.custom().setConnectionManager(connectionManager).setMaxConnTotal(1)
            .disableAutomaticRetries().setDefaultRequestConfig(requestBuilder.build())
            .setDefaultSocketConfig(
                    SocketConfig.custom().setTcpNoDelay(true).setSoTimeout(socketTimeout).build())
            .setDefaultCredentialsProvider(credentialsProvider).setSSLSocketFactory(myFactory)
            .setRequestExecutor(new HttpRequestExecutor(socketTimeout))
            .setRedirectStrategy(new DefaultRedirectStrategy()).build();

}

From source file:org.apache.manifoldcf.crawler.connectors.confluence.ConfluenceSession.java

public ConfluenceSession(String clientId, String clientSecret, String protocol, String host, int port,
        String path, String proxyHost, int proxyPort, String proxyDomain, String proxyUsername,
        String proxyPassword) throws ManifoldCFException {
    this.host = new HttpHost(host, port, protocol);
    this.path = path;
    this.clientId = clientId;
    this.clientSecret = clientSecret;

    int socketTimeout = 900000;
    int connectionTimeout = 60000;

    javax.net.ssl.SSLSocketFactory httpsSocketFactory = KeystoreManagerFactory.getTrustingSecureSocketFactory();
    SSLConnectionSocketFactory myFactory = new SSLConnectionSocketFactory(
            new InterruptibleSocketFactory(httpsSocketFactory, connectionTimeout),
            SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);

    connectionManager = new PoolingHttpClientConnectionManager();

    CredentialsProvider credentialsProvider = new BasicCredentialsProvider();

    // If authentication needed, set that
    if (clientId != null) {
        credentialsProvider.setCredentials(AuthScope.ANY,
                new UsernamePasswordCredentials(clientId, clientSecret));
    }/*from  w  w w  .j  a v  a  2 s.co m*/

    RequestConfig.Builder requestBuilder = RequestConfig.custom().setCircularRedirectsAllowed(true)
            .setSocketTimeout(socketTimeout).setStaleConnectionCheckEnabled(true).setExpectContinueEnabled(true)
            .setConnectTimeout(connectionTimeout).setConnectionRequestTimeout(socketTimeout);

    // If there's a proxy, set that too.
    if (proxyHost != null && proxyHost.length() > 0) {

        // Configure proxy authentication
        if (proxyUsername != null && proxyUsername.length() > 0) {
            if (proxyPassword == null)
                proxyPassword = "";
            if (proxyDomain == null)
                proxyDomain = "";

            credentialsProvider.setCredentials(new AuthScope(proxyHost, proxyPort),
                    new NTCredentials(proxyUsername, proxyPassword, currentHost, proxyDomain));
        }

        HttpHost proxy = new HttpHost(proxyHost, proxyPort);
        requestBuilder.setProxy(proxy);
    }

    httpClient = HttpClients.custom().setConnectionManager(connectionManager).setMaxConnTotal(1)
            .disableAutomaticRetries().setDefaultRequestConfig(requestBuilder.build())
            .setDefaultSocketConfig(
                    SocketConfig.custom().setTcpNoDelay(true).setSoTimeout(socketTimeout).build())
            .setDefaultCredentialsProvider(credentialsProvider).setSSLSocketFactory(myFactory)
            .setRequestExecutor(new HttpRequestExecutor(socketTimeout))
            .setRedirectStrategy(new DefaultRedirectStrategy()).build();
}

From source file:org.alfresco.rad.test.AlfrescoTestRunner.java

/**
 * Call a remote Alfresco server and have the test run there.
 *
 * @param method   the test method to run
 * @param notifier/*  w  ww  .ja v a  2 s. c o  m*/
 * @param desc
 */
protected void callProxiedChild(FrameworkMethod method, RunNotifier notifier, Description desc) {
    notifier.fireTestStarted(desc);

    String className = method.getMethod().getDeclaringClass().getCanonicalName();
    String methodName = method.getName();
    if (null != methodName) {
        className += "#" + methodName;
    }

    // Login credentials for Alfresco Repo
    // TODO: Maybe configure credentials in props...
    CredentialsProvider provider = new BasicCredentialsProvider();
    UsernamePasswordCredentials credentials = new UsernamePasswordCredentials("admin", "admin");
    provider.setCredentials(AuthScope.ANY, credentials);

    // Create HTTP Client with credentials
    CloseableHttpClient httpclient = HttpClientBuilder.create().setDefaultCredentialsProvider(provider).build();

    // Create the GET Request for the Web Script that will run the test
    String testWebScriptUrl = "/service/testing/test.xml?clazz=" + className.replace("#", "%23");
    //System.out.println("AlfrescoTestRunner: Invoking Web Script for test execution: " + testWebScriptUrl);
    HttpGet get = new HttpGet(getContextRoot(method) + testWebScriptUrl);

    try {
        // Send proxied request and read response
        HttpResponse resp = httpclient.execute(get);
        InputStream is = resp.getEntity().getContent();
        InputStreamReader ir = new InputStreamReader(is);
        BufferedReader br = new BufferedReader(ir);
        String body = "";
        String line;
        while ((line = br.readLine()) != null) {
            body += line + "\n";
        }

        // Process response
        if (body.length() > 0) {
            DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
            DocumentBuilder dBuilder = null;
            dBuilder = dbFactory.newDocumentBuilder();
            Document doc = dBuilder.parse(new InputSource(new StringReader(body)));

            Element root = doc.getDocumentElement();
            NodeList results = root.getElementsByTagName("result");
            if (null != results && results.getLength() > 0) {
                String result = results.item(0).getFirstChild().getNodeValue();
                if (SUCCESS.equals(result)) {
                    notifier.fireTestFinished(desc);
                } else {
                    boolean failureFired = false;
                    NodeList throwableNodes = root.getElementsByTagName("throwable");
                    for (int tid = 0; tid < throwableNodes.getLength(); tid++) {
                        String throwableBody = null;
                        Object object = null;
                        Throwable throwable = null;
                        throwableBody = throwableNodes.item(tid).getFirstChild().getNodeValue();
                        if (null != throwableBody) {
                            try {
                                object = objectFromString(throwableBody);
                            } catch (ClassNotFoundException e) {
                            }
                            if (null != object && object instanceof Throwable) {
                                throwable = (Throwable) object;
                            }
                        }
                        if (null == throwable) {
                            throwable = new Throwable("Unable to process exception body: " + throwableBody);
                        }

                        notifier.fireTestFailure(new Failure(desc, throwable));
                        failureFired = true;
                    }
                    if (!failureFired) {
                        notifier.fireTestFailure(new Failure(desc, new Throwable(
                                "There was an error but we can't figure out what it was, sorry!")));
                    }
                }
            } else {
                notifier.fireTestFailure(new Failure(desc,
                        new Throwable("Unable to process response for proxied test request: " + body)));
            }
        } else {
            notifier.fireTestFailure(new Failure(desc, new Throwable(
                    "Attempt to proxy test into running Alfresco instance failed, no response received")));
        }
    } catch (IOException e) {
        notifier.fireTestFailure(new Failure(desc, e));
    } catch (ParserConfigurationException e) {
        notifier.fireTestFailure(new Failure(desc, e));
    } catch (SAXException e) {
        notifier.fireTestFailure(new Failure(desc, e));
    } finally {
        try {
            httpclient.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}