Example usage for org.apache.http.impl.auth SPNegoSchemeFactory SPNegoSchemeFactory

List of usage examples for org.apache.http.impl.auth SPNegoSchemeFactory SPNegoSchemeFactory

Introduction

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

Prototype

public SPNegoSchemeFactory(final boolean stripPort) 

Source Link

Usage

From source file:org.ege.httpclient.ClientAuthentication.java

public static void main(String[] args) throws Exception {
    CredentialsProvider credsProvider = new BasicCredentialsProvider();
    credsProvider.setCredentials(new AuthScope(null, -1), new UsernamePasswordCredentials("alice", "alice"));

    Lookup<AuthSchemeProvider> basicAuthSchemeRegistry = RegistryBuilder.<AuthSchemeProvider>create()
            .register(AuthSchemes.BASIC, new BasicSchemeFactory()).build();
    Lookup<AuthSchemeProvider> spnegoAuthSchemeRegistry = RegistryBuilder.<AuthSchemeProvider>create()
            .register(AuthSchemes.SPNEGO, new SPNegoSchemeFactory(true)).build();

    CloseableHttpClient httpclient = HttpClients.custom().setDefaultCredentialsProvider(credsProvider)
            .setDefaultAuthSchemeRegistry(spnegoAuthSchemeRegistry).build();

    //Lookup<AuthSchemeProvider> authProviders = RegistryBuilder.<AuthSchemeProvider>create().register(AuthSchemes.BASIC, new BasicSchemeFactory()).build();
    //Lookup<AuthSchemeProvider> authRegistry = <...>

    //HttpClientContext context = HttpClientContext.create();
    //context.setCredentialsProvider(credsProvider);
    //context.setAuthSchemeRegistry(authRegistry);

    try {/*  w w w .  java2  s  . c  o  m*/
        HttpGet httpget = new HttpGet("http://lcom501d/hooks/hdr.cgi");

        System.out.println("Executing request " + httpget.getRequestLine());
        CloseableHttpResponse response = httpclient.execute(httpget);
        try {
            System.out.println("----------------------------------------");
            System.out.println(response.getStatusLine());
            EntityUtils.consume(response.getEntity());
        } finally {
            response.close();
        }
    } finally {
        httpclient.close();
    }
}

From source file:com.teradata.tempto.internal.hadoop.hdfs.SpnegoHttpRequestsExecutor.java

private HttpContext createSpnegoAwareHttpContext() {
    HttpClientContext httpContext = HttpClientContext.create();
    Lookup<AuthSchemeProvider> authSchemeRegistry = RegistryBuilder.<AuthSchemeProvider>create()
            .register(AuthSchemes.SPNEGO, new SPNegoSchemeFactory(true)).build();
    httpContext.setAuthSchemeRegistry(authSchemeRegistry);

    BasicCredentialsProvider credentialsProvider = new BasicCredentialsProvider();
    credentialsProvider.setCredentials(new AuthScope(null, -1, null), new NullCredentials());
    httpContext.setCredentialsProvider(credentialsProvider);
    return httpContext;
}

From source file:org.apache.hadoop.gateway.hive.HiveHttpClientDispatch.java

protected HttpResponse executeKerberosDispatch(HttpUriRequest outboundRequest, DefaultHttpClient client)
        throws IOException, ClientProtocolException {
    //DefaultHttpClient client = new DefaultHttpClient();
    SPNegoSchemeFactory spNegoSF = new SPNegoSchemeFactory(/* stripPort */true);
    // spNegoSF.setSpengoGenerator(new BouncySpnegoTokenGenerator());
    client.getAuthSchemes().register(AuthPolicy.SPNEGO, spNegoSF);
    client.getCredentialsProvider().setCredentials(new AuthScope(/* host */null, /* port */-1, /* realm */null),
            EMPTY_JAAS_CREDENTIALS);//from   w w w .  ja  va  2s  . c  o  m
    return client.execute(outboundRequest);
}

From source file:org.apache.ambari.server.controller.internal.AppCookieManager.java

/**
 * Returns hadoop.auth cookie, doing needed SPNego authentication
 * /*from  w  w  w  . j  a va  2  s  .  c  om*/
 * @param endpoint
 *          the URL of the Hadoop service
 * @param refresh
 *          flag indicating wehther to refresh the cookie, if
 *          <code>true</code>, we do a new SPNego authentication and refresh
 *          the cookie even if the cookie already exists in local cache
 * @return hadoop.auth cookie value
 * @throws IOException
 *           in case of problem getting hadoop.auth cookie
 */
public String getAppCookie(String endpoint, boolean refresh) throws IOException {

    HttpUriRequest outboundRequest = new HttpGet(endpoint);
    URI uri = outboundRequest.getURI();
    String scheme = uri.getScheme();
    String host = uri.getHost();
    int port = uri.getPort();
    String path = uri.getPath();
    if (!refresh) {
        String appCookie = endpointCookieMap.get(endpoint);
        if (appCookie != null) {
            return appCookie;
        }
    }

    clearAppCookie(endpoint);

    DefaultHttpClient client = new DefaultHttpClient();
    SPNegoSchemeFactory spNegoSF = new SPNegoSchemeFactory(/* stripPort */true);
    // spNegoSF.setSpengoGenerator(new BouncySpnegoTokenGenerator());
    client.getAuthSchemes().register(AuthPolicy.SPNEGO, spNegoSF);
    client.getCredentialsProvider().setCredentials(new AuthScope(/* host */null, /* port */-1, /* realm */null),
            EMPTY_JAAS_CREDENTIALS);

    String hadoopAuthCookie = null;
    HttpResponse httpResponse = null;
    try {
        HttpHost httpHost = new HttpHost(host, port, scheme);
        HttpRequest httpRequest = new HttpOptions(path);
        httpResponse = client.execute(httpHost, httpRequest);
        Header[] headers = httpResponse.getHeaders(SET_COOKIE);
        hadoopAuthCookie = getHadoopAuthCookieValue(headers);
        if (hadoopAuthCookie == null) {
            LOG.error("SPNego authentication failed, can not get hadoop.auth cookie for URL: " + endpoint);
            throw new IOException("SPNego authentication failed, can not get hadoop.auth cookie");
        }
    } finally {
        if (httpResponse != null) {
            HttpEntity entity = httpResponse.getEntity();
            if (entity != null) {
                entity.getContent().close();
            }
        }

    }

    hadoopAuthCookie = HADOOP_AUTH_EQ + quote(hadoopAuthCookie);
    setAppCookie(endpoint, hadoopAuthCookie);
    if (LOG.isInfoEnabled()) {
        LOG.info("Successful SPNego authentication to URL:" + uri.toString());
    }
    return hadoopAuthCookie;
}

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;
    }// www.  j  a v a2  s .  com
    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:org.apache.hadoop.gateway.dispatch.AppCookieManager.java

/**
 * Fetches hadoop.auth cookie from hadoop service authenticating using SpNego
 * //  w  w  w  .  jav  a2 s .  co  m
 * @param outboundRequest
 *          out going request
 * @param refresh
 *          flag indicating whether to refresh the cached cookie
 * @return hadoop.auth cookie from hadoop service authenticating using SpNego
 * @throws IOException
 *           in case of errors
 */
public String getAppCookie(HttpUriRequest outboundRequest, boolean refresh) throws IOException {

    URI uri = outboundRequest.getURI();
    String scheme = uri.getScheme();
    String host = uri.getHost();
    int port = uri.getPort();
    if (!refresh) {
        if (appCookie != null) {
            return appCookie;
        }
    }

    DefaultHttpClient client = new DefaultHttpClient();
    SPNegoSchemeFactory spNegoSF = new SPNegoSchemeFactory(/* stripPort */true);
    // spNegoSF.setSpengoGenerator(new BouncySpnegoTokenGenerator());
    client.getAuthSchemes().register(AuthPolicy.SPNEGO, spNegoSF);
    client.getCredentialsProvider().setCredentials(new AuthScope(/* host */null, /* port */-1, /* realm */null),
            EMPTY_JAAS_CREDENTIALS);

    clearAppCookie();
    String hadoopAuthCookie = null;
    HttpResponse httpResponse = null;
    try {
        HttpHost httpHost = new HttpHost(host, port, scheme);
        HttpRequest httpRequest = createKerberosAuthenticationRequest(outboundRequest);
        httpResponse = client.execute(httpHost, httpRequest);
        Header[] headers = httpResponse.getHeaders(SET_COOKIE);
        hadoopAuthCookie = getHadoopAuthCookieValue(headers);
        EntityUtils.consume(httpResponse.getEntity());
        if (hadoopAuthCookie == null) {
            LOG.failedSPNegoAuthn(uri.toString());
            auditor.audit(Action.AUTHENTICATION, uri.toString(), ResourceType.URI, ActionOutcome.FAILURE);
            throw new IOException("SPNego authn failed, can not get hadoop.auth cookie");
        }
    } finally {
        if (httpResponse != null) {
            HttpEntity entity = httpResponse.getEntity();
            if (entity != null) {
                entity.getContent().close();
            }
        }

    }
    LOG.successfulSPNegoAuthn(uri.toString());
    auditor.audit(Action.AUTHENTICATION, uri.toString(), ResourceType.URI, ActionOutcome.SUCCESS);
    hadoopAuthCookie = HADOOP_AUTH_EQ + quote(hadoopAuthCookie);
    setAppCookie(hadoopAuthCookie);
    return appCookie;
}

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

/**
 * Gets a HTTP client.// ww  w.j  ava  2  s  .c o m
 * @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.pentaho.di.trans.ael.websocket.SessionConfigurator.java

private Header spnegoAuthenticate(boolean stripPort, URI uri) throws Exception {
    SPNegoSchemeFactory spNegoSchemeFactory = new SPNegoSchemeFactory(stripPort);
    // using newInstance method instead of create method to be compatible httpclient library from 4.2 to 4.5
    // the create method was introduced at version 4.3
    SPNegoScheme spNegoScheme = (SPNegoScheme) spNegoSchemeFactory.newInstance(null);
    spNegoScheme.processChallenge(AUTHENTICATE_HEADER);
    return spNegoScheme.authenticate(credentials, new HttpGet(""), getContext(uri));
}

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

public Lookup<AuthSchemeProvider> buildAuthSchemeProviderLookup() {
    RegistryBuilder<AuthSchemeProvider> registryBuilder = RegistryBuilder.create();

    for (String type : authTypes) {
        switch (type.trim()) {
        case "NTLM":
            registryBuilder.register(AuthSchemes.NTLM, new AuthSchemeProvider() {
                @Override// www  . j  a v a2  s .  c o m
                public AuthScheme create(HttpContext httpContext) {
                    return new NTLMScheme(new JCIFSEngine());
                }
            });
            break;
        case "BASIC":
            registryBuilder.register(AuthSchemes.BASIC,
                    new BasicSchemeFactory(Charset.forName(Utils.DEFAULT_CHARACTER_SET)));
            String value = username + ":" + password;
            byte[] encodedValue = Base64.encodeBase64(value.getBytes(StandardCharsets.UTF_8));
            headers.add(new BasicHeader("Authorization", "Basic " + new String(encodedValue)));
            break;
        case "DIGEST":
            registryBuilder.register(AuthSchemes.DIGEST, new DigestSchemeFactory());
            break;
        case "KERBEROS":
            if (kerberosConfigFile != null) {
                System.setProperty("java.security.krb5.conf", kerberosConfigFile);
            } else {
                File krb5Config;
                String domain = host.replaceAll(".*\\.(?=.*\\.)", "");
                try {
                    krb5Config = createKrb5Configuration(domain);
                } catch (IOException e) {
                    throw new RuntimeException("could not create the krb5 config file" + e.getMessage(), e);
                }
                System.setProperty("java.security.krb5.conf", krb5Config.toURI().toString());
            }

            if (kerberosLoginConfigFile != null) {
                System.setProperty("java.security.auth.login.config", kerberosLoginConfigFile);
            } else {
                File loginConfig;
                try {
                    loginConfig = createLoginConfig();
                } catch (IOException e) {
                    throw new RuntimeException(
                            "could not create the kerberos login config file" + e.getMessage(), e);
                }
                System.setProperty("java.security.auth.login.config", loginConfig.toURI().toString());
            }

            if (password != null) {
                System.setProperty(KrbHttpLoginModule.PAS, password);
            }
            if (username != null) {
                System.setProperty(KrbHttpLoginModule.USR, username);
            }

            System.setProperty("javax.security.auth.useSubjectCredsOnly", "false");

            boolean skipPort = Boolean.parseBoolean(skipPortAtKerberosDatabaseLookup);
            registryBuilder.register(AuthSchemes.KERBEROS, new KerberosSchemeFactory(skipPort));
            registryBuilder.register(AuthSchemes.SPNEGO, new SPNegoSchemeFactory(skipPort));
            break;
        case AuthTypes.ANONYMOUS:
            break;
        default:
            throw new IllegalStateException(
                    "Unsupported '" + HttpClientInputs.AUTH_TYPE + "'authentication scheme: " + type);
        }
    }
    return registryBuilder.build();
}

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

public Lookup<AuthSchemeProvider> buildAuthSchemeProviderLookup() {
    RegistryBuilder<AuthSchemeProvider> registryBuilder = RegistryBuilder.create();

    for (String type : authTypes) {
        switch (type.trim()) {
        case "NTLM":
            registryBuilder.register(AuthSchemes.NTLM, new AuthSchemeProvider() {
                @Override//w w  w .  jav  a 2s  .c  o  m
                public AuthScheme create(HttpContext httpContext) {
                    return new NTLMScheme(new JCIFSEngine());
                }
            });
            break;
        case "BASIC":
            registryBuilder.register(AuthSchemes.BASIC, new BasicSchemeFactory(Charset.forName("UTF-8")));
            String value = username + ":" + password;
            byte[] encodedValue = Base64.encodeBase64(value.getBytes(StandardCharsets.UTF_8));
            headers.add(new BasicHeader("Authorization", "Basic " + new String(encodedValue)));
            break;
        case "DIGEST":
            registryBuilder.register(AuthSchemes.DIGEST, new DigestSchemeFactory());
            break;
        case "KERBEROS":
            if (getSettingsKey().equals(System.getProperty("oohttpclient.krb.last.settings"))) {
                break;
            }
            if (kerberosConfigFile != null) {
                System.setProperty("java.security.krb5.conf", kerberosConfigFile);
            } else {
                File krb5Config;
                String domain = host.replaceAll(".*\\.(?=.*\\.)", "");
                try {
                    krb5Config = createKrb5Configuration(domain);
                } catch (IOException e) {
                    throw new RuntimeException("could not create the krb5 config file" + e.getMessage(), e);
                }
                System.setProperty("java.security.krb5.conf", krb5Config.toURI().toString());
            }

            if (kerberosLoginConfigFile != null) {
                System.setProperty("java.security.auth.login.config", kerberosLoginConfigFile);
            } else {
                File loginConfig;
                try {
                    loginConfig = createLoginConfig();
                } catch (IOException e) {
                    throw new RuntimeException(
                            "could not create the kerberos login config file" + e.getMessage(), e);
                }
                System.setProperty("java.security.auth.login.config", loginConfig.toURI().toString());
            }

            //todo fix security issue
            if (password != null) {
                System.setProperty(KrbHttpLoginModule.PAS, password);
            }
            if (username != null) {
                System.setProperty(KrbHttpLoginModule.USR, username);
            }

            System.setProperty("javax.security.auth.useSubjectCredsOnly", "false");

            boolean skipPort = Boolean.parseBoolean(skipPortAtKerberosDatabaseLookup);
            registryBuilder.register(AuthSchemes.KERBEROS, new KerberosSchemeFactory(skipPort));
            registryBuilder.register(AuthSchemes.SPNEGO, new SPNegoSchemeFactory(skipPort));
            System.setProperty("oohttpclient.krb.last.settings", getSettingsKey());
            break;
        default:
            throw new IllegalStateException(
                    "Unsupported '" + HttpClientInputs.AUTH_TYPE + "'authentication scheme: " + type);
        }
    }
    return registryBuilder.build();
}