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

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

Introduction

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

Prototype

Credentials

Source Link

Usage

From source file:com.dlmu.heipacker.crawler.client.ClientKerberosAuthentication.java

public static void main(String[] args) throws Exception {

    System.setProperty("java.security.auth.login.config", "login.conf");
    System.setProperty("java.security.krb5.conf", "krb5.conf");
    System.setProperty("sun.security.krb5.debug", "true");
    System.setProperty("javax.security.auth.useSubjectCredsOnly", "false");

    DefaultHttpClient httpclient = new DefaultHttpClient();
    try {//from   w ww.j a v  a  2  s  .  co m
        httpclient.getAuthSchemes().register(AuthPolicy.SPNEGO, new SPNegoSchemeFactory());

        Credentials use_jaas_creds = new Credentials() {

            public String getPassword() {
                return null;
            }

            public Principal getUserPrincipal() {
                return null;
            }

        };

        httpclient.getCredentialsProvider().setCredentials(new AuthScope(null, -1, null), use_jaas_creds);

        HttpUriRequest request = new HttpGet("http://kerberoshost/");
        HttpResponse response = httpclient.execute(request);
        HttpEntity entity = response.getEntity();

        System.out.println("----------------------------------------");
        System.out.println(response.getStatusLine());
        System.out.println("----------------------------------------");
        if (entity != null) {
            System.out.println(EntityUtils.toString(entity));
        }
        System.out.println("----------------------------------------");

        // This ensures the connection gets released back to the manager
        EntityUtils.consume(entity);

    } finally {
        // When HttpClient instance is no longer needed,
        // shut down the connection manager to ensure
        // immediate deallocation of all system resources
        httpclient.getConnectionManager().shutdown();
    }
}

From source file:com.nesscomputing.tinyhttp.HttpFetcherCredentialsProvider.java

@Override
public Credentials getCredentials(final AuthScope authScope) {
    return new Credentials() {

        @Override//  www .  j ava 2  s  .c om
        public Principal getUserPrincipal() {
            return new BasicUserPrincipal(login);
        }

        @Override
        public String getPassword() {
            return pw;
        }
    };
}

From source file:com.nesscomputing.httpclient.factory.httpclient4.InternalCredentialsProvider.java

@Override
public Credentials getCredentials(final AuthScope authScope) {
    for (final HttpClientAuthProvider authProvider : authProviders) {
        if (authProvider.acceptRequest(authScope.getScheme(), authScope.getHost(), authScope.getPort(),
                authScope.getRealm())) {
            return new Credentials() {

                @Override/*  ww w .jav  a  2s.c o m*/
                public Principal getUserPrincipal() {
                    return new BasicUserPrincipal(authProvider.getUser());
                }

                @Override
                public String getPassword() {
                    return authProvider.getPassword();
                }

            };
        }
    }
    return null;
}

From source file:org.openscore.content.httpclient.build.auth.CredentialsProviderBuilder.java

public CredentialsProvider buildCredentialsProvider() {
    CredentialsProvider credentialsProvider = new BasicCredentialsProvider();

    if (!StringUtils.isEmpty(username)) {
        Credentials credentials;//from   www . ja  va  2 s  . co  m
        if (authTypes.contains(AuthTypes.NTLM)) {
            String[] domainAndUsername = getDomainUsername(username);
            credentials = new NTCredentials(domainAndUsername[1], password, host, domainAndUsername[0]);
        } else {
            credentials = new UsernamePasswordCredentials(username, password);
        }
        credentialsProvider.setCredentials(new AuthScope(host, Integer.parseInt(port)), credentials);
    } else if (authTypes.contains(AuthTypes.KERBEROS)) {
        credentialsProvider.setCredentials(new AuthScope(host, Integer.parseInt(port)), new Credentials() {
            @Override
            public Principal getUserPrincipal() {
                return null;
            }

            @Override
            public String getPassword() {
                return null;
            }
        });
    }

    if (!StringUtils.isEmpty(proxyUsername)) {
        int intProxyPort = 8080;
        if (!StringUtils.isEmpty(proxyPort)) {
            intProxyPort = Integer.parseInt(proxyPort);
        }
        credentialsProvider.setCredentials(new AuthScope(proxyHost, intProxyPort),
                new UsernamePasswordCredentials(proxyUsername, proxyPassword));
    }

    return credentialsProvider;
}

From source file:io.cloudslang.content.httpclient.build.auth.CredentialsProviderBuilder.java

public CredentialsProvider buildCredentialsProvider() {
    CredentialsProvider credentialsProvider = new BasicCredentialsProvider();

    if (!StringUtils.isEmpty(username)) {
        Credentials credentials;/*from  w w  w.j  ava 2 s .  com*/
        if (authTypes.contains(AuthTypes.NTLM)) {
            String[] domainAndUsername = getDomainUsername(username);
            credentials = new NTCredentials(domainAndUsername[1], password, host, domainAndUsername[0]);
        } else {
            credentials = new UsernamePasswordCredentials(username, password);
        }
        credentialsProvider.setCredentials(new AuthScope(host, Integer.parseInt(port)), credentials);
    } else if (authTypes.contains(AuthTypes.KERBEROS)) {
        credentialsProvider.setCredentials(new AuthScope(host, Integer.parseInt(port)), new Credentials() {
            @Override
            public Principal getUserPrincipal() {
                return null;
            }

            @Override
            public String getPassword() {
                return null;
            }
        });
    }

    if (!StringUtils.isEmpty(proxyUsername)) {
        int intProxyPort = 8080;
        if (!StringUtils.isEmpty(proxyPort)) {
            intProxyPort = Utils.validatePortNumber(proxyPort);
        }
        credentialsProvider.setCredentials(new AuthScope(proxyHost, intProxyPort),
                new UsernamePasswordCredentials(proxyUsername, proxyPassword));
    }

    return credentialsProvider;
}

From source file:org.restheart.test.integration.SecurityAuthTokenIT.java

@Test
public void testAuthToken() throws Exception {
    Response resp = adminExecutor.execute(Request.Get(rootUri));

    HttpResponse httpResp = resp.returnResponse();
    assertNotNull(httpResp);//  w  w  w . ja v  a  2  s  . co  m

    StatusLine statusLine = httpResp.getStatusLine();
    assertNotNull(statusLine);

    assertEquals("check authorized", HttpStatus.SC_OK, statusLine.getStatusCode());

    Header[] _authToken = httpResp.getHeaders(AUTH_TOKEN_HEADER.toString());
    Header[] _authTokenValid = httpResp.getHeaders(AUTH_TOKEN_VALID_HEADER.toString());
    Header[] _authTokenLocation = httpResp.getHeaders(AUTH_TOKEN_LOCATION_HEADER.toString());

    assertNotNull("check not null auth token header", _authToken);
    assertNotNull("check not null auth token valid header", _authTokenValid);
    assertNotNull("check not null auth token location header", _authTokenLocation);

    assertTrue("check not empty array auth token header array ", _authToken.length == 1);
    assertTrue("check not empty array auth token valid header array", _authTokenValid.length == 1);
    assertTrue("check not empty array auth token location header array", _authTokenLocation.length == 1);

    assertTrue("check not empty array auth token header value not null or empty",
            _authToken[0] != null && _authToken[0].getValue() != null && !_authToken[0].getValue().isEmpty());
    assertTrue("check not empty array auth token valid value not null or empty", _authTokenValid[0] != null
            && _authTokenValid[0].getValue() != null && !_authTokenValid[0].getValue().isEmpty());
    assertTrue("check not empty array auth token location  not null or empty", _authTokenLocation[0] != null
            && _authTokenLocation[0].getValue() != null && !_authTokenLocation[0].getValue().isEmpty());

    Response resp2 = unauthExecutor.auth(new Credentials() {
        @Override
        public Principal getUserPrincipal() {
            return new BasicUserPrincipal("admin");
        }

        @Override
        public String getPassword() {
            return _authToken[0].getValue();
        }
    }).execute(Request.Get(rootUri));

    HttpResponse httpResp2 = resp2.returnResponse();
    assertNotNull(httpResp2);

    StatusLine statusLine2 = httpResp2.getStatusLine();
    assertNotNull(statusLine2);

    assertEquals("check authorized via auth token", HttpStatus.SC_OK, statusLine2.getStatusCode());
}

From source file:org.apache.solr.client.solrj.impl.Krb5HttpClientConfigurer.java

public void configure(DefaultHttpClient httpClient, SolrParams config) {
    super.configure(httpClient, config);

    if (System.getProperty(LOGIN_CONFIG_PROP) != null) {
        String configValue = System.getProperty(LOGIN_CONFIG_PROP);

        if (configValue != null) {
            logger.info("Setting up SPNego auth with config: " + configValue);
            final String useSubjectCredsProp = "javax.security.auth.useSubjectCredsOnly";
            String useSubjectCredsVal = System.getProperty(useSubjectCredsProp);

            // "javax.security.auth.useSubjectCredsOnly" should be false so that the underlying
            // authentication mechanism can load the credentials from the JAAS configuration.
            if (useSubjectCredsVal == null) {
                System.setProperty(useSubjectCredsProp, "false");
            } else if (!useSubjectCredsVal.toLowerCase(Locale.ROOT).equals("false")) {
                // Don't overwrite the prop value if it's already been written to something else,
                // but log because it is likely the Credentials won't be loaded correctly.
                logger.warn("System Property: " + useSubjectCredsProp + " set to: " + useSubjectCredsVal
                        + " not false.  SPNego authentication may not be successful.");
            }// w w  w.  j  a v  a 2 s.c  o  m

            javax.security.auth.login.Configuration.setConfiguration(jaasConfig);
            //Enable only SPNEGO authentication scheme.
            AuthSchemeRegistry registry = new AuthSchemeRegistry();
            registry.register(AuthSchemes.SPNEGO, new SPNegoSchemeFactory(true, false));
            httpClient.setAuthSchemes(registry);
            // Get the credentials from the JAAS configuration rather than here
            Credentials useJaasCreds = new Credentials() {
                public String getPassword() {
                    return null;
                }

                public Principal getUserPrincipal() {
                    return null;
                }
            };

            SolrPortAwareCookieSpecFactory cookieFactory = new SolrPortAwareCookieSpecFactory();
            httpClient.getCookieSpecs().register(cookieFactory.POLICY_NAME, cookieFactory);
            httpClient.getParams().setParameter(ClientPNames.COOKIE_POLICY, cookieFactory.POLICY_NAME);

            httpClient.getCredentialsProvider().setCredentials(AuthScope.ANY, useJaasCreds);

            httpClient.addRequestInterceptor(bufferedEntityInterceptor);
        } else {
            httpClient.getCredentialsProvider().clear();
        }
    }
}

From source file:org.apache.kylin.engine.mr.common.HadoopStatusGetter.java

private String getHttpResponseWithKerberosAuth(String url) throws IOException {
    String krb5ConfigPath = System.getProperty("java.security.krb5.conf");
    if (krb5ConfigPath == null) {
        krb5ConfigPath = DEFAULT_KRB5_CONFIG_LOCATION;
    }/*from   w w w .jav a  2  s  .c o  m*/
    boolean skipPortAtKerberosDatabaseLookup = true;
    System.setProperty("java.security.krb5.conf", krb5ConfigPath);
    System.setProperty("sun.security.krb5.debug", "true");
    System.setProperty("javax.security.auth.useSubjectCredsOnly", "false");

    DefaultHttpClient client = new DefaultHttpClient();
    AuthSchemeRegistry authSchemeRegistry = new AuthSchemeRegistry();
    authSchemeRegistry.register(AuthPolicy.SPNEGO, new SPNegoSchemeFactory(skipPortAtKerberosDatabaseLookup));
    client.setAuthSchemes(authSchemeRegistry);

    BasicCredentialsProvider credentialsProvider = new BasicCredentialsProvider();
    Credentials useJaasCreds = new Credentials() {
        public String getPassword() {
            return null;
        }

        public Principal getUserPrincipal() {
            return null;
        }
    };
    credentialsProvider.setCredentials(new AuthScope(null, -1, null), useJaasCreds);
    client.setCredentialsProvider(credentialsProvider);

    String response = null;
    while (response == null) {
        if (url.startsWith("https://")) {
            registerEasyHttps();
        }
        if (url.contains("anonymous=true") == false) {
            url += url.contains("?") ? "&" : "?";
            url += "anonymous=true";
        }
        HttpGet httpget = new HttpGet(url);
        httpget.addHeader("accept", "application/json");
        try {
            HttpResponse httpResponse = client.execute(httpget);
            String redirect = null;
            org.apache.http.Header h = httpResponse.getFirstHeader("Location");
            if (h != null) {
                redirect = h.getValue();
                if (isValidURL(redirect) == false) {
                    logger.info("Get invalid redirect url, skip it: " + redirect);
                    Thread.sleep(1000L);
                    continue;
                }
            } else {
                h = httpResponse.getFirstHeader("Refresh");
                if (h != null) {
                    String s = h.getValue();
                    int cut = s.indexOf("url=");
                    if (cut >= 0) {
                        redirect = s.substring(cut + 4);

                        if (isValidURL(redirect) == false) {
                            logger.info("Get invalid redirect url, skip it: " + redirect);
                            Thread.sleep(1000L);
                            continue;
                        }
                    }
                }
            }

            if (redirect == null) {
                response = IOUtils.toString(httpResponse.getEntity().getContent(), Charset.defaultCharset());
                logger.debug("Job " + mrJobId + " get status check result.\n");
            } else {
                url = redirect;
                logger.debug("Job " + mrJobId + " check redirect url " + url + ".\n");
            }
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
            logger.error(e.getMessage());
        } finally {
            httpget.releaseConnection();
        }
    }

    return response;
}

From source file:com.telefonica.iot.cygnus.backends.http.HttpClientFactory.java

/**
 * Gets a HTTP client./*  ww w  . ja v  a 2s .  c  om*/
 * @param ssl True if SSL connections are desired. False otherwise
 * @param krb5Auth.
 * @return A http client obtained from the (SSL) Connections Manager.
 */
public DefaultHttpClient getHttpClient(boolean ssl, boolean krb5Auth) {
    DefaultHttpClient httpClient;

    if (ssl) {
        httpClient = new DefaultHttpClient(sslConnectionsManager);
    } else {
        httpClient = new DefaultHttpClient(connectionsManager);
    } // if else

    if (krb5Auth) {
        // http://stackoverflow.com/questions/21629132/httpclient-set-credentials-for-kerberos-authentication

        System.setProperty("java.security.auth.login.config", loginConfFile);
        System.setProperty("java.security.krb5.conf", krb5ConfFile);
        System.setProperty("sun.security.krb5.debug", "false");
        System.setProperty("javax.security.auth.useSubjectCredsOnly", "false");
        Credentials jaasCredentials = new Credentials() {

            @Override
            public String getPassword() {
                return null;
            } // getPassword

            @Override
            public Principal getUserPrincipal() {
                return null;
            } // getUserPrincipal

        };

        // 'true' means the port is stripped from the principal names
        SPNegoSchemeFactory spnegoSchemeFactory = new SPNegoSchemeFactory(true);
        httpClient.getAuthSchemes().register(AuthPolicy.SPNEGO, spnegoSchemeFactory);
        httpClient.getCredentialsProvider().setCredentials(new AuthScope(null, -1, null), jaasCredentials);
    } // if

    return httpClient;
}

From source file:org.apache.solr.client.solrj.impl.Krb5HttpClientBuilder.java

public SolrHttpClientBuilder getBuilder(SolrHttpClientBuilder builder) {
    if (System.getProperty(LOGIN_CONFIG_PROP) != null) {
        String configValue = System.getProperty(LOGIN_CONFIG_PROP);

        if (configValue != null) {
            logger.info("Setting up SPNego auth with config: " + configValue);
            final String useSubjectCredsProp = "javax.security.auth.useSubjectCredsOnly";
            String useSubjectCredsVal = System.getProperty(useSubjectCredsProp);

            // "javax.security.auth.useSubjectCredsOnly" should be false so that the underlying
            // authentication mechanism can load the credentials from the JAAS configuration.
            if (useSubjectCredsVal == null) {
                System.setProperty(useSubjectCredsProp, "false");
            } else if (!useSubjectCredsVal.toLowerCase(Locale.ROOT).equals("false")) {
                // Don't overwrite the prop value if it's already been written to something else,
                // but log because it is likely the Credentials won't be loaded correctly.
                logger.warn("System Property: " + useSubjectCredsProp + " set to: " + useSubjectCredsVal
                        + " not false.  SPNego authentication may not be successful.");
            }//from ww w.j  av a  2  s.com

            javax.security.auth.login.Configuration.setConfiguration(jaasConfig);
            //Enable only SPNEGO authentication scheme.

            builder.setAuthSchemeRegistryProvider(() -> {
                Lookup<AuthSchemeProvider> authProviders = RegistryBuilder.<AuthSchemeProvider>create()
                        .register(AuthSchemes.SPNEGO, new SPNegoSchemeFactory(true, false)).build();
                return authProviders;
            });
            // Get the credentials from the JAAS configuration rather than here
            Credentials useJaasCreds = new Credentials() {
                public String getPassword() {
                    return null;
                }

                public Principal getUserPrincipal() {
                    return null;
                }
            };

            HttpClientUtil.setCookiePolicy(SolrPortAwareCookieSpecFactory.POLICY_NAME);

            builder.setCookieSpecRegistryProvider(() -> {
                SolrPortAwareCookieSpecFactory cookieFactory = new SolrPortAwareCookieSpecFactory();

                Lookup<CookieSpecProvider> cookieRegistry = RegistryBuilder.<CookieSpecProvider>create()
                        .register(SolrPortAwareCookieSpecFactory.POLICY_NAME, cookieFactory).build();

                return cookieRegistry;
            });

            builder.setDefaultCredentialsProvider(() -> {
                CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
                credentialsProvider.setCredentials(AuthScope.ANY, useJaasCreds);
                return credentialsProvider;
            });
            HttpClientUtil.addRequestInterceptor(bufferedEntityInterceptor);
        }
    }

    return builder;
}