Example usage for org.apache.http.client.config AuthSchemes SPNEGO

List of usage examples for org.apache.http.client.config AuthSchemes SPNEGO

Introduction

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

Prototype

String SPNEGO

To view the source code for org.apache.http.client.config AuthSchemes SPNEGO.

Click Source Link

Document

SPNEGO Authentication scheme.

Usage

From source file:org.apache.zeppelin.submarine.hadoop.YarnClient.java

private static HttpClient buildSpengoHttpClient() {
    HttpClientBuilder builder = HttpClientBuilder.create();
    Lookup<AuthSchemeProvider> authSchemeRegistry = RegistryBuilder.<AuthSchemeProvider>create()
            .register(AuthSchemes.SPNEGO, new SPNegoSchemeFactory(true)).build();
    builder.setDefaultAuthSchemeRegistry(authSchemeRegistry);
    BasicCredentialsProvider credentialsProvider = new BasicCredentialsProvider();
    credentialsProvider.setCredentials(new AuthScope(null, -1, null), new Credentials() {
        @Override/*from   w  w  w . j a  v a  2  s  . c  o  m*/
        public Principal getUserPrincipal() {
            return null;
        }

        @Override
        public String getPassword() {
            return null;
        }
    });
    builder.setDefaultCredentialsProvider(credentialsProvider);

    // Avoid output WARN: Cookie rejected
    RequestConfig globalConfig = RequestConfig.custom().setCookieSpec(CookieSpecs.IGNORE_COOKIES).build();
    builder.setDefaultRequestConfig(globalConfig);

    CloseableHttpClient httpClient = builder.build();

    return httpClient;
}

From source file:org.jboss.as.test.integration.security.common.Utils.java

/**
 * Returns response body for the given URL request as a String. It also checks if the returned HTTP status code is the
 * expected one. If the server returns {@link HttpServletResponse#SC_UNAUTHORIZED} and an username is provided, then the
 * given user is authenticated against Kerberos and a new request is executed under the new subject.
 *
 * @param uri URI to which the request should be made
 * @param user Username/*w  w  w.  ja  va  2 s .  c o m*/
 * @param pass Password
 * @param expectedStatusCode expected status code returned from the requested server
 * @return HTTP response body
 * @throws IOException
 * @throws URISyntaxException
 * @throws PrivilegedActionException
 * @throws LoginException
 */
public static String makeCallWithKerberosAuthn(final URI uri, final String user, final String pass,
        final int expectedStatusCode)
        throws IOException, URISyntaxException, PrivilegedActionException, LoginException {
    LOGGER.trace("Requesting URI: " + uri);
    Registry<AuthSchemeProvider> authSchemeRegistry = RegistryBuilder.<AuthSchemeProvider>create()
            .register(AuthSchemes.SPNEGO, new JBossNegotiateSchemeFactory(true)).build();

    CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
    credentialsProvider.setCredentials(new AuthScope(null, -1, null), new NullHCCredentials());

    final Krb5LoginConfiguration krb5Configuration = new Krb5LoginConfiguration(getLoginConfiguration());

    try (final CloseableHttpClient httpClient = HttpClientBuilder.create()
            .setDefaultAuthSchemeRegistry(authSchemeRegistry).setDefaultCredentialsProvider(credentialsProvider)
            .build()) {

        final HttpGet httpGet = new HttpGet(uri);
        final HttpResponse response = httpClient.execute(httpGet);
        int statusCode = response.getStatusLine().getStatusCode();
        if (HttpServletResponse.SC_UNAUTHORIZED != statusCode || StringUtils.isEmpty(user)) {
            assertEquals("Unexpected HTTP response status code.", expectedStatusCode, statusCode);
            return EntityUtils.toString(response.getEntity());
        }
        final HttpEntity entity = response.getEntity();
        final Header[] authnHeaders = response.getHeaders("WWW-Authenticate");
        assertTrue("WWW-Authenticate header is present", authnHeaders != null && authnHeaders.length > 0);
        final Set<String> authnHeaderValues = new HashSet<String>();
        for (final Header header : authnHeaders) {
            authnHeaderValues.add(header.getValue());
        }
        assertTrue("WWW-Authenticate: Negotiate header is missing", authnHeaderValues.contains("Negotiate"));

        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("HTTP response was SC_UNAUTHORIZED, let's authenticate the user " + user);
        }
        if (entity != null)
            EntityUtils.consume(entity);

        // Use our custom configuration to avoid reliance on external config
        Configuration.setConfiguration(krb5Configuration);
        // 1. Authenticate to Kerberos.
        final LoginContext lc = loginWithKerberos(krb5Configuration, user, pass);

        // 2. Perform the work as authenticated Subject.
        final String responseBody = Subject.doAs(lc.getSubject(), new PrivilegedExceptionAction<String>() {
            public String run() throws Exception {
                final HttpResponse response = httpClient.execute(httpGet);
                int statusCode = response.getStatusLine().getStatusCode();
                assertEquals("Unexpected status code returned after the authentication.", expectedStatusCode,
                        statusCode);
                return EntityUtils.toString(response.getEntity());
            }
        });
        lc.logout();
        return responseBody;
    } finally {
        krb5Configuration.resetConfiguration();
    }
}

From source file:org.jboss.as.test.integration.security.common.Utils.java

/**
 * Creates request against SPNEGO protected web-app with FORM fallback. It tries to login using SPNEGO first - if it fails,
 * FORM is used.// w w w. j a  v a2 s .  co  m
 *
 * @param contextUrl
 * @param page
 * @param user
 * @param pass
 * @param expectedStatusCode
 * @return
 * @throws IOException
 * @throws URISyntaxException
 * @throws PrivilegedActionException
 * @throws LoginException
 */
public static String makeHttpCallWithFallback(final String contextUrl, final String page, final String user,
        final String pass, final int expectedStatusCode)
        throws IOException, URISyntaxException, PrivilegedActionException, LoginException {
    final String strippedContextUrl = StringUtils.stripEnd(contextUrl, "/");
    final String url = strippedContextUrl + page;
    LOGGER.trace("Requesting URL: " + url);
    String unauthorizedPageBody = null;
    final Krb5LoginConfiguration krb5Configuration = new Krb5LoginConfiguration(getLoginConfiguration());

    Registry<AuthSchemeProvider> authSchemeRegistry = RegistryBuilder.<AuthSchemeProvider>create()
            .register(AuthSchemes.SPNEGO, new JBossNegotiateSchemeFactory(true)).build();

    CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
    credentialsProvider.setCredentials(new AuthScope(null, -1, null), new NullHCCredentials());

    final CloseableHttpClient httpClient = HttpClientBuilder.create()
            .setDefaultAuthSchemeRegistry(authSchemeRegistry).setDefaultCredentialsProvider(credentialsProvider)
            .setRedirectStrategy(REDIRECT_STRATEGY).setConnectionManager(new BasicHttpClientConnectionManager())
            .build();

    try {
        final HttpGet httpGet = new HttpGet(url);
        final HttpResponse response = httpClient.execute(httpGet);
        int statusCode = response.getStatusLine().getStatusCode();
        if (HttpServletResponse.SC_UNAUTHORIZED != statusCode || StringUtils.isEmpty(user)) {
            assertEquals("Unexpected HTTP response status code.", expectedStatusCode, statusCode);
            return EntityUtils.toString(response.getEntity());
        }
        final Header[] authnHeaders = response.getHeaders("WWW-Authenticate");
        assertTrue("WWW-Authenticate header is present", authnHeaders != null && authnHeaders.length > 0);
        final Set<String> authnHeaderValues = new HashSet<String>();
        for (final Header header : authnHeaders) {
            authnHeaderValues.add(header.getValue());
        }
        assertTrue("WWW-Authenticate: Negotiate header is missing", authnHeaderValues.contains("Negotiate"));

        LOGGER.debug("HTTP response was SC_UNAUTHORIZED, let's authenticate the user " + user);
        unauthorizedPageBody = EntityUtils.toString(response.getEntity());

        // Use our custom configuration to avoid reliance on external config
        Configuration.setConfiguration(krb5Configuration);
        // 1. Authenticate to Kerberos.
        final LoginContext lc = loginWithKerberos(krb5Configuration, user, pass);

        // 2. Perform the work as authenticated Subject.
        final String responseBody = Subject.doAs(lc.getSubject(), new PrivilegedExceptionAction<String>() {
            public String run() throws Exception {
                final HttpResponse response = httpClient.execute(httpGet);
                int statusCode = response.getStatusLine().getStatusCode();
                assertEquals("Unexpected status code returned after the authentication.", expectedStatusCode,
                        statusCode);
                return EntityUtils.toString(response.getEntity());
            }
        });
        lc.logout();
        return responseBody;
    } catch (LoginException e) {
        assertNotNull(unauthorizedPageBody);
        assertTrue(unauthorizedPageBody.contains("j_security_check"));

        HttpPost httpPost = new HttpPost(strippedContextUrl + "/j_security_check");
        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
        nameValuePairs.add(new BasicNameValuePair("j_username", user));
        nameValuePairs.add(new BasicNameValuePair("j_password", pass));
        httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
        final HttpResponse response = httpClient.execute(httpPost);
        int statusCode = response.getStatusLine().getStatusCode();
        assertEquals("Unexpected status code returned after the authentication.", expectedStatusCode,
                statusCode);
        return EntityUtils.toString(response.getEntity());
    } finally {
        // When HttpClient instance is no longer needed,
        // shut down the connection manager to ensure
        // immediate deallocation of all system resources
        httpClient.close();
        // reset login configuration
        krb5Configuration.resetConfiguration();
    }
}

From source file:org.mitre.dsmiley.httpproxy.ProxyServlet.java

/**
 * Called from {@link #init(javax.servlet.ServletConfig)}. HttpClient offers
 * many opportunities for customization. By default, <a href=
 * "http://hc.apache.org/httpcomponents-client-ga/httpclient/apidocs/org/apache/http/impl/client/SystemDefaultHttpClient.html">
 * SystemDefaultHttpClient</a> is used if available, otherwise it falls back
 * to://from w  w w. j  av a2s. c om
 * 
 * <pre>
 * new DefaultHttpClient(new ThreadSafeClientConnManager(), hcParams)
 * </pre>
 * 
 * SystemDefaultHttpClient uses PoolingClientConnectionManager. In any case,
 * it should be thread-safe.
 */
protected HttpClient createHttpClient(HttpParams hcParams) {
    try {

        String negotiateURL = getConfigParam("negotiate.url");
        String negotiateSPN = getConfigParam("negotiate.spn");
        if (negotiateURL != null && negotiateSPN != null) {
            System.out.println("negotiate url:" + negotiateURL);
            System.out.println("negotiate spn:" + negotiateSPN);
            // initialize the Windows security Context to get the negotiate
            // client token
            IWindowsSecurityContext clientContext = null;
            IWindowsCredentialsHandle clientCredentials = null;
            clientContext = WindowsSecurityContextImpl.getCurrent(SECURITY_PACKAGE, negotiateSPN);
            clientCredentials = WindowsCredentialsHandleImpl.getCurrent(SECURITY_PACKAGE);
            clientCredentials.initialize();
            String username = WindowsAccountImpl.getCurrentUsername();
            System.out.println("credentials for user " + username + " get prepared");
            byte[] token = clientContext.getToken();
            // encode the token with Base64 to be able to add it to the http
            // header
            String clientToken = Base64.encodeBase64String(token);
            System.out.println("clientToken" + clientToken);
            // if there is only a negotiate url the rest of the
            // authorization is based on cookies
            // so we need to support them.
            CookieStore cookieStore = new BasicCookieStore();
            RequestConfig globalConfig = RequestConfig.custom().setCookieSpec(CookieSpecs.DEFAULT).build();
            HttpClientContext context = HttpClientContext.create();
            proxyContext = context;
            context.setCookieStore(cookieStore);
            HttpClient httpClient = HttpClients.custom().disableRedirectHandling()
                    .setDefaultRequestConfig(globalConfig).setDefaultCookieStore(cookieStore).build();

            // first we need to act as a normal browser to get a http 401
            // with negotiate header
            doActAsBrowser = true;
            HttpGet browserHttpGet = new HttpGet(negotiateURL);
            addBrowserHeader(browserHttpGet);
            HttpResponse rep = httpClient.execute(browserHttpGet, context);

            if (rep.getStatusLine().getStatusCode() == 401) {
                System.out.println("negotiate requested - sending negotiate client token");
                HttpGet negotiateHttpGet = new HttpGet(negotiateURL);
                addBrowserHeader(negotiateHttpGet);
                negotiateHttpGet.addHeader("Authorization", "Negotiate " + clientToken);
                HttpResponse response = httpClient.execute(negotiateHttpGet, context);
                System.out.println(
                        "http result code of negotiate request:" + response.getStatusLine().getStatusCode());
                // now the url needs to be called periodically to keep the
                // cookie and connection alive
                String refreshTimeString = getConfigParam("negotiate.refreshtime");
                long refreshTime = 1000000;
                if (refreshTimeString != null) {
                    refreshTime = Long.parseLong(refreshTimeString);
                }
                HttpClientRefreshThread thread = new HttpClientRefreshThread(refreshTime, negotiateURL);
                thread.start();
                List<org.apache.http.cookie.Cookie> cookies = context.getCookieStore().getCookies();
                cookieString = "";
                int size = cookies.size() - 1;
                for (int i = 0; i < cookies.size(); i++) {
                    cookieString += cookies.get(i).getName();
                    cookieString += "=";
                    cookieString += cookies.get(i).getValue();
                    if (i != size)
                        cookieString += "; ";
                }
            } else {
                System.out.println("No negotiate requested");
            }
        } else {
            if (!WinHttpClients.isWinAuthAvailable()) {
                System.out.println("Integrated Win auth is not supported!!!");
            } else {
                HttpClientBuilder builder = WinHttpClients.custom();
                Registry<AuthSchemeProvider> authSchemeRegistry = RegistryBuilder.<AuthSchemeProvider>create()
                        .register(AuthSchemes.BASIC, new BasicSchemeFactory())
                        .register(AuthSchemes.DIGEST, new DigestSchemeFactory())
                        .register(AuthSchemes.SPNEGO, new SPNegoSchemeFactory())
                        .register(AuthSchemes.NTLM, new NTLMSchemeFactory())
                        .register(AuthSchemes.KERBEROS, new KerberosSchemeFactory()).build();
                builder.setDefaultAuthSchemeRegistry(authSchemeRegistry);
                String username = getConfigParam("user");
                String password = getConfigParam("password");
                String domain = getConfigParam("domain");
                String host = getConfigParam("host");
                if (username != null) {
                    NTCredentials cred = new NTCredentials(username, password, host, domain);
                    CredentialsProvider credsProvider = new WindowsCredentialsProvider(
                            new SystemDefaultCredentialsProvider());
                    credsProvider.setCredentials(AuthScope.ANY, cred);
                    builder.setDefaultCredentialsProvider(credsProvider);
                }
                builder.disableCookieManagement();
                builder.disableRedirectHandling();
                return builder.build();
            }

            // as of HttpComponents v4.2, this class is better since it uses
            // System
            // Properties:
            Class<?> clientClazz = Class.forName("org.apache.http.impl.client.SystemDefaultHttpClient");
            Constructor<?> constructor = clientClazz.getConstructor(HttpParams.class);
            return (HttpClient) constructor.newInstance(hcParams);
        }
    } catch (ClassNotFoundException e) {
        // no problem; use v4.1 below
    } catch (Exception e) {
        throw new RuntimeException(e);
    }

    // Fallback on using older client:
    return new DefaultHttpClient(new ThreadSafeClientConnManager(), hcParams);
}