Example usage for org.apache.http.client CredentialsProvider setCredentials

List of usage examples for org.apache.http.client CredentialsProvider setCredentials

Introduction

In this page you can find the example usage for org.apache.http.client CredentialsProvider setCredentials.

Prototype

void setCredentials(AuthScope authscope, Credentials credentials);

Source Link

Document

Sets the Credentials credentials for the given authentication scope.

Usage

From source file:org.jmonkey.external.bintray.BintrayApiClient.java

private CloseableHttpClient createAuthenticatedClient() {

    CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
    credentialsProvider.setCredentials(AuthScope.ANY,
            new UsernamePasswordCredentials(config.getUser(), config.getApiKey()));

    return HttpClients.custom().setDefaultCookieStore(new BasicCookieStore()).setUserAgent(userAgent)
            .setRedirectStrategy(new LaxRedirectStrategy()).setDefaultCredentialsProvider(credentialsProvider)
            .build();// w  ww .  ja  v a 2 s  .  com
}

From source file:com.ontotext.s4.gdbaas.createRepo.service.GdbaasClient.java

/**
 * Sets up a HTTPContext for authentication
 *///from   ww  w.j a  v a2  s.co m
private void setupContext() {
    ctx = HttpClientContext.create();
    UsernamePasswordCredentials creds = new UsernamePasswordCredentials(keyId, password);
    CredentialsProvider credsProvider = new BasicCredentialsProvider();
    credsProvider.setCredentials(AuthScope.ANY, creds);
    ctx.setCredentialsProvider(credsProvider);
}

From source file:org.callimachusproject.client.HttpClientFactoryTest.java

@Test
public void testAuthentication() throws Exception {
    HttpGet get = new HttpGet("http://example.com/protected");
    HttpContext localContext = new BasicHttpContext();
    List<String> authpref = Collections.singletonList(AuthPolicy.BASIC);
    AuthScope scope = new AuthScope("example.com", -1);
    UsernamePasswordCredentials cred = new UsernamePasswordCredentials("Aladdin", "open sesame");
    CredentialsProvider credsProvider = new BasicCredentialsProvider();
    credsProvider.setCredentials(scope, cred);
    localContext.setAttribute(ClientContext.CREDS_PROVIDER, credsProvider);
    get.getParams().setBooleanParameter(ClientPNames.HANDLE_AUTHENTICATION, true);
    get.getParams().setParameter(AuthPNames.TARGET_AUTH_PREF, authpref);
    BasicHttpResponse unauth = new BasicHttpResponse(_401);
    unauth.setHeader("WWW-Authenticate", "Basic realm=\"insert realm\"");
    responses.add(unauth);//from   w  w  w  .j  a va  2s.  c o  m
    responses.add(new BasicHttpResponse(_200));
    client.execute(get, new ResponseHandler<Void>() {
        public Void handleResponse(HttpResponse response) throws ClientProtocolException, IOException {
            assertEquals(_200.getStatusCode(), response.getStatusLine().getStatusCode());
            assertContains("Authorization: Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==", asString(response.getEntity()));
            return null;
        }
    }, localContext);
}

From source file:org.smssecure.smssecure.mms.LegacyMmsConnection.java

protected CloseableHttpClient constructHttpClient() throws IOException {
    RequestConfig config = RequestConfig.custom().setConnectTimeout(20 * 1000)
            .setConnectionRequestTimeout(20 * 1000).setSocketTimeout(20 * 1000).setMaxRedirects(20).build();

    URL mmsc = new URL(apn.getMmsc());
    CredentialsProvider credsProvider = new BasicCredentialsProvider();

    if (apn.hasAuthentication()) {
        credsProvider.setCredentials(
                new AuthScope(mmsc.getHost(), mmsc.getPort() > -1 ? mmsc.getPort() : mmsc.getDefaultPort()),
                new UsernamePasswordCredentials(apn.getUsername(), apn.getPassword()));
    }/*from  w w  w.  ja va  2s .co m*/

    return HttpClients.custom().setConnectionReuseStrategy(new NoConnectionReuseStrategyHC4())
            .setRedirectStrategy(new LaxRedirectStrategy())
            .setUserAgent(SilencePreferences.getMmsUserAgent(context, USER_AGENT))
            .setConnectionManager(new BasicHttpClientConnectionManager()).setDefaultRequestConfig(config)
            .setDefaultCredentialsProvider(credsProvider).build();
}

From source file:edu.lternet.pasta.client.LoginClient.java

/**
 * Perform a PASTA login operation using the user's credentials. Because there
 * is not a formal PASTA login method, we will use a simple query for the Data
 * Package Manager service, which will perform the necessary user
 * authentication (this step should be replaced with a formal PASTA
 * "login service method").//from w  ww  .j a v a2 s. c o m
 * 
 * @param uid
 *          The user identifier.
 * @param password
 *          The user password.
 * 
 * @return The authentication token as a String object if the login is
 *         successful.
 */
private String login(String uid, String password) {

    String token = null;
    String username = PastaClient.composeDistinguishedName(uid);

    /*
     * The following set of code sets up Preemptive Authentication for the HTTP
     * CLIENT and is done so at the warning stated within the Apache
     * Http-Components Client tutorial here:
     * http://hc.apache.org/httpcomponents-
     * client-ga/tutorial/html/authentication.html#d5e1031
     */

    // Define host parameters
    HttpHost httpHost = new HttpHost(this.pastaHost, this.pastaPort, this.pastaProtocol);
    CloseableHttpClient httpClient = HttpClientBuilder.create().build();

    // Define user authentication credentials that will be used with the host
    AuthScope authScope = new AuthScope(httpHost.getHostName(), httpHost.getPort());
    UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(username, password);
    CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
    credentialsProvider.setCredentials(authScope, credentials);

    // 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(httpHost, basicAuth);

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

    HttpGet httpGet = new HttpGet(this.LOGIN_URL);
    HttpResponse response = null;
    Header[] headers = null;
    Integer statusCode = null;

    try {

        response = httpClient.execute(httpHost, httpGet, context);
        headers = response.getAllHeaders();
        statusCode = (Integer) response.getStatusLine().getStatusCode();
        logger.info("STATUS: " + statusCode.toString());

    } catch (UnsupportedEncodingException e) {
        logger.error(e);
        e.printStackTrace();
    } catch (ClientProtocolException e) {
        logger.error(e);
        e.printStackTrace();
    } catch (IOException e) {
        logger.error(e);
        e.printStackTrace();
    } finally {
        closeHttpClient(httpClient);
    }

    if (statusCode == HttpStatus.SC_OK) {

        String headerName = null;
        String headerValue = null;

        // Loop through all headers looking for the "Set-Cookie" header.
        for (int i = 0; i < headers.length; i++) {
            headerName = headers[i].getName();

            if (headerName.equals("Set-Cookie")) {
                headerValue = headers[i].getValue();
                token = this.getAuthToken(headerValue);
            }

        }

    }

    return token;
}

From source file:MainFrame.HttpCommunicator.java

public void setCombos(JComboBox comboGroups, JComboBox comboDates, LessonTableModel tableModel)
        throws MalformedURLException, IOException {
    BufferedReader in = null;/*from  w  w w.  j a va2 s  .  co  m*/
    if (SingleDataHolder.getInstance().isProxyActivated) {
        CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
        credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(
                SingleDataHolder.getInstance().proxyLogin, SingleDataHolder.getInstance().proxyPassword));

        HttpClient client = HttpClientBuilder.create().setDefaultCredentialsProvider(credentialsProvider)
                .build();

        HttpHost proxy = new HttpHost(SingleDataHolder.getInstance().proxyIpAdress,
                SingleDataHolder.getInstance().proxyPort);

        RequestConfig config = RequestConfig.custom().setProxy(proxy).build();

        HttpPost post = new HttpPost(SingleDataHolder.getInstance().hostAdress + "index.php");
        post.setConfig(config);

        StringBody head = new StringBody(new JSONObject().toString(), ContentType.TEXT_PLAIN);

        MultipartEntityBuilder builder = MultipartEntityBuilder.create();
        builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
        builder.addPart("apideskviewer.getAllLessons", head);

        HttpEntity entity = builder.build();
        post.setEntity(entity);
        ResponseHandler<String> responseHandler = new BasicResponseHandler();
        String response = client.execute(post, responseHandler);
        System.out.println("responseBody : " + response);

        InputStream stream = new ByteArrayInputStream(response.getBytes(StandardCharsets.UTF_8));

        in = new BufferedReader(new InputStreamReader(stream));
    } else {
        URL obj = new URL(SingleDataHolder.getInstance().hostAdress);
        HttpURLConnection con = (HttpURLConnection) obj.openConnection();

        //add reuqest header
        con.setRequestMethod("POST");
        con.setRequestProperty("User-Agent", USER_AGENT);
        con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");

        String urlParameters = "apideskviewer.getAllLessons={}";

        // Send post request
        con.setDoOutput(true);
        DataOutputStream wr = new DataOutputStream(con.getOutputStream());
        wr.writeBytes(urlParameters);
        wr.flush();
        wr.close();

        int responseCode = con.getResponseCode();
        System.out.println("\nSending 'POST' request to URL : " + SingleDataHolder.getInstance().hostAdress);
        System.out.println("Post parameters : " + urlParameters);
        System.out.println("Response Code : " + responseCode);

        in = new BufferedReader(new InputStreamReader(con.getInputStream()));
    }

    JSONParser parser = new JSONParser();
    try {
        Object parsedResponse = parser.parse(in);

        JSONObject jsonParsedResponse = (JSONObject) parsedResponse;

        for (int i = 0; i < jsonParsedResponse.size(); i++) {
            String s = (String) jsonParsedResponse.get(String.valueOf(i));
            String[] splittedPath = s.split("/");
            DateFormat DF = new SimpleDateFormat("yyyyMMdd");
            Date d = DF.parse(splittedPath[1].replaceAll(".bin", ""));
            Lesson lesson = new Lesson(splittedPath[0], d, false);
            String group = splittedPath[0];
            String date = new SimpleDateFormat("dd.MM.yyyy").format(d);

            if (((DefaultComboBoxModel) comboGroups.getModel()).getIndexOf(group) == -1) {
                comboGroups.addItem(group);
            }
            if (((DefaultComboBoxModel) comboDates.getModel()).getIndexOf(date) == -1) {
                comboDates.addItem(date);
            }
            tableModel.addLesson(lesson);
        }
    } catch (Exception ex) {
    }
}

From source file:it.larusba.neo4j.jdbc.http.driver.CypherExecutor.java

/**
 * Default constructor.//from  ww  w  . ja  va 2  s  .  c o  m
 *
 * @param host       Hostname of the Neo4j instance.
 * @param port       HTTP port of the Neo4j instance.
 * @param properties Properties of the url connection.
 * @throws SQLException
 */
public CypherExecutor(String host, Integer port, Properties properties) throws SQLException {
    // Create the http client builder
    HttpClientBuilder builder = HttpClients.custom();
    // Adding authentication to the http client if needed
    if (properties.containsKey("user") && properties.containsKey("password")) {
        CredentialsProvider credsProvider = new BasicCredentialsProvider();
        credsProvider.setCredentials(new AuthScope(host, port), new UsernamePasswordCredentials(
                properties.get("user").toString(), properties.get("password").toString()));
        builder.setDefaultCredentialsProvider(credsProvider);
    }
    // Setting user-agent
    StringBuilder sb = new StringBuilder();
    sb.append("Neo4j JDBC Driver");
    if (properties.containsKey("userAgent")) {
        sb.append(" via ");
        sb.append(properties.getProperty("userAgent"));
    }
    builder.setUserAgent(sb.toString());
    // Create the http client
    this.http = builder.build();

    // Create the url endpoint
    StringBuffer sbEndpoint = new StringBuffer();
    sbEndpoint.append("http://").append(host).append(":").append(port).append("/db/data/transaction");
    this.transactionUrl = sbEndpoint.toString();

    // Setting autocommit
    this.setAutoCommit(Boolean.valueOf(properties.getProperty("autoCommit", "true")));
}

From source file:com.redhat.jenkins.nodesharing.RestEndpoint.java

private @Nonnull HttpClientContext getAuthenticatingContext(@Nonnull HttpRequestBase method) {
    AuthCache authCache = new BasicAuthCache();
    BasicScheme basicAuth = new BasicScheme();
    authCache.put(URIUtils.extractHost(method.getURI()), basicAuth);

    CredentialsProvider provider = new BasicCredentialsProvider();
    provider.setCredentials(AuthScope.ANY, new org.apache.http.auth.UsernamePasswordCredentials(
            creds.getUsername(), creds.getPassword().getPlainText()));
    HttpClientContext context = HttpClientContext.create();
    context.setCredentialsProvider(provider);
    context.setAuthCache(authCache);/*w w  w.j a  va2 s  . co m*/
    return context;
}

From source file:org.zalando.stups.tokens.AccessTokenRefresher.java

private AccessToken createToken(final AccessTokenConfiguration tokenConfig) {
    try {//  ww w . j  ava2s. c o m

        // collect credentials
        final ClientCredentials clientCredentials = configuration.getClientCredentialsProvider().get();
        final UserCredentials userCredentials = configuration.getUserCredentialsProvider().get();

        // prepare basic auth credentials
        final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
        credentialsProvider.setCredentials(
                new AuthScope(configuration.getAccessTokenUri().getHost(),
                        configuration.getAccessTokenUri().getPort()),
                new UsernamePasswordCredentials(clientCredentials.getId(), clientCredentials.getSecret()));

        // create a new client that targets our host with basic auth enabled
        final CloseableHttpClient client = HttpClients.custom()
                .setDefaultCredentialsProvider(credentialsProvider).build();
        final HttpHost host = new HttpHost(configuration.getAccessTokenUri().getHost(),
                configuration.getAccessTokenUri().getPort(), configuration.getAccessTokenUri().getScheme());
        final HttpPost request = new HttpPost(configuration.getAccessTokenUri());

        // prepare the request body

        final List<NameValuePair> values = new ArrayList<NameValuePair>() {

            {
                add(new BasicNameValuePair("grant_type", "password"));
                add(new BasicNameValuePair("username", userCredentials.getUsername()));
                add(new BasicNameValuePair("password", userCredentials.getPassword()));
                add(new BasicNameValuePair("scope", joinScopes(tokenConfig.getScopes())));
            }
        };
        request.setEntity(new UrlEncodedFormEntity(values));

        // enable basic auth for the request
        final AuthCache authCache = new BasicAuthCache();
        final BasicScheme basicAuth = new BasicScheme();
        authCache.put(host, basicAuth);

        final HttpClientContext localContext = HttpClientContext.create();
        localContext.setAuthCache(authCache);

        // execute!
        final CloseableHttpResponse response = client.execute(host, request, localContext);
        try {

            // success status code?
            final int status = response.getStatusLine().getStatusCode();
            if (status < 200 || status >= 300) {
                throw AccessTokenEndpointException.from(response);
            }

            // get json response
            final HttpEntity entity = response.getEntity();
            final AccessTokenResponse accessTokenResponse = OBJECT_MAPPER
                    .readValue(EntityUtils.toByteArray(entity), AccessTokenResponse.class);

            // create new access token object
            final Date validUntil = new Date(
                    System.currentTimeMillis() + (accessTokenResponse.expiresInSeconds * 1000));

            return new AccessToken(accessTokenResponse.getAccessToken(), accessTokenResponse.getTokenType(),
                    accessTokenResponse.getExpiresInSeconds(), validUntil);
        } finally {
            response.close();
        }
    } catch (Throwable t) {
        throw new AccessTokenEndpointException(t.getMessage(), t);
    }
}