Example usage for org.apache.http.client.params AuthPolicy SPNEGO

List of usage examples for org.apache.http.client.params AuthPolicy SPNEGO

Introduction

In this page you can find the example usage for org.apache.http.client.params AuthPolicy SPNEGO.

Prototype

String SPNEGO

To view the source code for org.apache.http.client.params AuthPolicy SPNEGO.

Click Source Link

Document

SPNEGO Authentication scheme.

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 w  w  .  j  a  v a2 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.eviware.soapui.support.httpclient.JCIFSTest.java

@Test
public void test() throws ParseException, IOException {
    try {/*  w ww.  j a  va  2  s  . c  o  m*/
        DefaultHttpClient httpClient = new DefaultHttpClient();

        httpClient.getAuthSchemes().register(AuthPolicy.NTLM, new NTLMSchemeFactory());
        httpClient.getAuthSchemes().register(AuthPolicy.SPNEGO, new NTLMSchemeFactory());

        NTCredentials creds = new NTCredentials("testuser", "kebabsalladT357", "", "");
        httpClient.getCredentialsProvider().setCredentials(AuthScope.ANY, creds);

        HttpHost target = new HttpHost("dev-appsrv01.eviware.local", 81, "http");
        HttpContext localContext = new BasicHttpContext();
        HttpGet httpget = new HttpGet("/");

        HttpResponse response1 = httpClient.execute(target, httpget, localContext);
        HttpEntity entity1 = response1.getEntity();

        //      System.out.println( "----------------------------------------" );
        //System.out.println( response1.getStatusLine() );
        //      System.out.println( "----------------------------------------" );
        if (entity1 != null) {
            //System.out.println( EntityUtils.toString( entity1 ) );
        }
        //      System.out.println( "----------------------------------------" );

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

        Assert.assertEquals(response1.getStatusLine().getStatusCode(), 200);
    } catch (UnknownHostException e) {
        /* ignore */
    } catch (HttpHostConnectException e) {
        /* ignore */
    } catch (SocketException e) {
        /* ignore */
    }

    Assert.assertTrue(true);
}

From source file:com.eviware.soapui.impl.wsdl.submit.filters.HttpAuthenticationRequestFilterTest.java

@Test
public void selectingAuthTypeNtlmReturnsNtlmEvenIfSpnegoRequested() {
    selectAuthMethod(CredentialsConfig.AuthType.NTLM);

    filter.filterAbstractHttpRequest(null, wsdlRequest);

    AuthScheme scheme = getSchemeFor(AuthPolicy.SPNEGO);
    assertThat(scheme, instanceOf(NTLMScheme.class));
}

From source file:com.eviware.soapui.impl.wsdl.submit.filters.HttpAuthenticationRequestFilterTest.java

@Test
public void selectingAuthTypeSpnegoReturnsSpnegoIfSpnegoRequested() {
    selectAuthMethod(CredentialsConfig.AuthType.SPNEGO_KERBEROS);

    filter.filterAbstractHttpRequest(null, wsdlRequest);

    AuthScheme scheme = getSchemeFor(AuthPolicy.SPNEGO);
    assertThat(scheme, instanceOf(NegotiateScheme.class));
}

From source file:org.jasig.portlet.calendar.adapter.exchange.NtlmAuthHttpClient.java

@Override
public void afterPropertiesSet() throws Exception {
    if (authenticationSchemes == null) {
        authenticationSchemes = new HashMap<String, AuthSchemeFactory>();
        final AuthSchemeFactory fac = new NTLMSchemeFactory();
        final AuthSchemeFactory bfac = new BasicSchemeFactory();
        authenticationSchemes.put(AuthPolicy.BASIC, bfac);
        authenticationSchemes.put(AuthPolicy.NTLM, fac);
        authenticationSchemes.put(AuthPolicy.SPNEGO, fac);
    }/*w  w w.j  a v a2  s  .  co  m*/
    setup();
    if (log.isDebugEnabled()) {
        log.debug("Support is available for the following authenticationSchemes="
                + authenticationSchemes.keySet());
    }
}

From source file:com.servoy.extensions.plugins.http.HttpClient.java

public HttpClient(IClientPluginAccess plugin) {
    client = new DefaultHttpClient();
    client.getParams().setParameter(ClientPNames.ALLOW_CIRCULAR_REDIRECTS, Boolean.TRUE);
    client.getAuthSchemes().register(AuthPolicy.NTLM, new NTLMSchemeFactory());
    client.getAuthSchemes().register(AuthPolicy.SPNEGO, new NegotiateSchemeFactory());
    this.plugin = plugin;

    try {/*from   ww  w  .j  av  a  2 s  . c  om*/
        final AllowedCertTrustStrategy allowedCertTrustStrategy = new AllowedCertTrustStrategy();
        SSLSocketFactory sf = new SSLSocketFactory(allowedCertTrustStrategy) {
            @Override
            public Socket connectSocket(Socket socket, InetSocketAddress remoteAddress,
                    InetSocketAddress localAddress, HttpParams params)
                    throws IOException, UnknownHostException, ConnectTimeoutException {
                if (socket instanceof SSLSocket) {
                    try {
                        Method s = socket.getClass().getMethod("setHost", String.class);
                        s.invoke(socket, remoteAddress.getHostName());
                    } catch (NoSuchMethodException ex) {
                    } catch (IllegalAccessException ex) {
                    } catch (InvocationTargetException ex) {
                    } catch (IllegalArgumentException ex) {
                    } catch (SecurityException ex) {
                    }
                }
                try {
                    return super.connectSocket(socket, remoteAddress, localAddress, params);
                } catch (SSLPeerUnverifiedException ex) {
                    X509Certificate[] lastCertificates = allowedCertTrustStrategy.getAndClearLastCertificates();
                    if (lastCertificates != null) {
                        // allow for next time
                        if (HttpClient.this.plugin.getApplicationType() == IClientPluginAccess.CLIENT
                                || HttpClient.this.plugin.getApplicationType() == IClientPluginAccess.RUNTIME) {
                            // show dialog
                            CertificateDialog dialog = new CertificateDialog(
                                    ((ISmartRuntimeWindow) HttpClient.this.plugin.getCurrentRuntimeWindow())
                                            .getWindow(),
                                    remoteAddress, lastCertificates);
                            if (dialog.shouldAccept()) {
                                allowedCertTrustStrategy.add(lastCertificates);
                                // try it again now with the new chain.
                                return super.connectSocket(socket, remoteAddress, localAddress, params);
                            }
                        } else {
                            Debug.error("Couldn't connect to " + remoteAddress
                                    + ", please make sure that the ssl certificates of that site are added to the java keystore."
                                    + "Download the keystore in the browser and update the java cacerts file in jre/lib/security: "
                                    + "keytool -import -file downloaded.crt -keystore cacerts");
                        }
                    }
                    throw ex;
                } finally {
                    // always just clear the last request.
                    allowedCertTrustStrategy.getAndClearLastCertificates();
                }

            }
        };
        Scheme https = new Scheme("https", 443, sf); //$NON-NLS-1$
        client.getConnectionManager().getSchemeRegistry().register(https);
    } catch (Exception e) {
        Debug.error("Can't register a https scheme", e); //$NON-NLS-1$
    }
}

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);/*w ww. java  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  ww w .  j ava2 s  .c  o m
 * @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;
}