Search in sources :

Example 16 with SPNegoSchemeFactory

use of org.apache.http.impl.auth.SPNegoSchemeFactory in project zeppelin by apache.

the class YarnClient method buildSpengoHttpClient.

// Kerberos authentication for simulated curling
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
        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;
}
Also used : RequestConfig(org.apache.http.client.config.RequestConfig) CloseableHttpClient(org.apache.http.impl.client.CloseableHttpClient) BasicCredentialsProvider(org.apache.http.impl.client.BasicCredentialsProvider) AuthScope(org.apache.http.auth.AuthScope) HttpClientBuilder(org.apache.http.impl.client.HttpClientBuilder) AuthSchemeProvider(org.apache.http.auth.AuthSchemeProvider) SPNegoSchemeFactory(org.apache.http.impl.auth.SPNegoSchemeFactory) Credentials(org.apache.http.auth.Credentials) KerberosPrincipal(javax.security.auth.kerberos.KerberosPrincipal) Principal(java.security.Principal)

Example 17 with SPNegoSchemeFactory

use of org.apache.http.impl.auth.SPNegoSchemeFactory in project zeppelin by apache.

the class BaseLivyInterpreter method createRestTemplate.

private RestTemplate createRestTemplate() {
    String keytabLocation = getProperty("zeppelin.livy.keytab");
    String principal = getProperty("zeppelin.livy.principal");
    boolean isSpnegoEnabled = StringUtils.isNotEmpty(keytabLocation) && StringUtils.isNotEmpty(principal);
    HttpClient httpClient = null;
    if (livyURL.startsWith("https:")) {
        try {
            SSLContext sslContext = getSslContext();
            SSLConnectionSocketFactory csf = new SSLConnectionSocketFactory(sslContext);
            HttpClientBuilder httpClientBuilder = HttpClients.custom().setSSLSocketFactory(csf);
            if (isSpnegoEnabled) {
                RequestConfig reqConfig = new RequestConfig() {

                    @Override
                    public boolean isAuthenticationEnabled() {
                        return true;
                    }
                };
                httpClientBuilder.setDefaultRequestConfig(reqConfig);
                Credentials credentials = new Credentials() {

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

                    @Override
                    public Principal getUserPrincipal() {
                        return null;
                    }
                };
                CredentialsProvider credsProvider = new BasicCredentialsProvider();
                credsProvider.setCredentials(AuthScope.ANY, credentials);
                httpClientBuilder.setDefaultCredentialsProvider(credsProvider);
                Registry<AuthSchemeProvider> authSchemeProviderRegistry = RegistryBuilder.<AuthSchemeProvider>create().register(AuthSchemes.SPNEGO, new SPNegoSchemeFactory()).build();
                httpClientBuilder.setDefaultAuthSchemeRegistry(authSchemeProviderRegistry);
            }
            httpClient = httpClientBuilder.build();
        } catch (Exception e) {
            throw new RuntimeException("Failed to create SSL HttpClient", e);
        }
    }
    RestTemplate restTemplate;
    if (isSpnegoEnabled) {
        if (httpClient == null) {
            restTemplate = new KerberosRestTemplate(keytabLocation, principal);
        } else {
            restTemplate = new KerberosRestTemplate(keytabLocation, principal, httpClient);
        }
    } else {
        if (httpClient == null) {
            restTemplate = new RestTemplate();
        } else {
            restTemplate = new RestTemplate(new HttpComponentsClientHttpRequestFactory(httpClient));
        }
    }
    restTemplate.getMessageConverters().add(0, new StringHttpMessageConverter(StandardCharsets.UTF_8));
    return restTemplate;
}
Also used : RequestConfig(org.apache.http.client.config.RequestConfig) BasicCredentialsProvider(org.apache.http.impl.client.BasicCredentialsProvider) SSLContext(javax.net.ssl.SSLContext) HttpClientBuilder(org.apache.http.impl.client.HttpClientBuilder) BasicCredentialsProvider(org.apache.http.impl.client.BasicCredentialsProvider) CredentialsProvider(org.apache.http.client.CredentialsProvider) SPNegoSchemeFactory(org.apache.http.impl.auth.SPNegoSchemeFactory) SSLConnectionSocketFactory(org.apache.http.conn.ssl.SSLConnectionSocketFactory) InterpreterException(org.apache.zeppelin.interpreter.InterpreterException) RestClientException(org.springframework.web.client.RestClientException) HttpServerErrorException(org.springframework.web.client.HttpServerErrorException) HttpClientErrorException(org.springframework.web.client.HttpClientErrorException) StringHttpMessageConverter(org.springframework.http.converter.StringHttpMessageConverter) KerberosRestTemplate(org.springframework.security.kerberos.client.KerberosRestTemplate) HttpClient(org.apache.http.client.HttpClient) RestTemplate(org.springframework.web.client.RestTemplate) KerberosRestTemplate(org.springframework.security.kerberos.client.KerberosRestTemplate) AuthSchemeProvider(org.apache.http.auth.AuthSchemeProvider) HttpComponentsClientHttpRequestFactory(org.springframework.http.client.HttpComponentsClientHttpRequestFactory) Credentials(org.apache.http.auth.Credentials)

Example 18 with SPNegoSchemeFactory

use of org.apache.http.impl.auth.SPNegoSchemeFactory in project hbase by apache.

the class TestSpnegoHttpServer method testAllowedClient.

@Test
public void testAllowedClient() throws Exception {
    // Create the subject for the client
    final Subject clientSubject = JaasKrbUtil.loginUsingKeytab(CLIENT_PRINCIPAL, clientKeytab);
    final Set<Principal> clientPrincipals = clientSubject.getPrincipals();
    // Make sure the subject has a principal
    assertFalse(clientPrincipals.isEmpty());
    // Get a TGT for the subject (might have many, different encryption types). The first should
    // be the default encryption type.
    Set<KerberosTicket> privateCredentials = clientSubject.getPrivateCredentials(KerberosTicket.class);
    assertFalse(privateCredentials.isEmpty());
    KerberosTicket tgt = privateCredentials.iterator().next();
    assertNotNull(tgt);
    // The name of the principal
    final String principalName = clientPrincipals.iterator().next().getName();
    // Run this code, logged in as the subject (the client)
    HttpResponse resp = Subject.doAs(clientSubject, new PrivilegedExceptionAction<HttpResponse>() {

        @Override
        public HttpResponse run() throws Exception {
            // Logs in with Kerberos via GSS
            GSSManager gssManager = GSSManager.getInstance();
            // jGSS Kerberos login constant
            Oid oid = new Oid("1.2.840.113554.1.2.2");
            GSSName gssClient = gssManager.createName(principalName, GSSName.NT_USER_NAME);
            GSSCredential credential = gssManager.createCredential(gssClient, GSSCredential.DEFAULT_LIFETIME, oid, GSSCredential.INITIATE_ONLY);
            HttpClientContext context = HttpClientContext.create();
            Lookup<AuthSchemeProvider> authRegistry = RegistryBuilder.<AuthSchemeProvider>create().register(AuthSchemes.SPNEGO, new SPNegoSchemeFactory(true, true)).build();
            HttpClient client = HttpClients.custom().setDefaultAuthSchemeRegistry(authRegistry).build();
            BasicCredentialsProvider credentialsProvider = new BasicCredentialsProvider();
            credentialsProvider.setCredentials(AuthScope.ANY, new KerberosCredentials(credential));
            URL url = new URL(getServerURL(server), "/echo?a=b");
            context.setTargetHost(new HttpHost(url.getHost(), url.getPort()));
            context.setCredentialsProvider(credentialsProvider);
            context.setAuthSchemeRegistry(authRegistry);
            HttpGet get = new HttpGet(url.toURI());
            return client.execute(get, context);
        }
    });
    assertNotNull(resp);
    assertEquals(HttpURLConnection.HTTP_OK, resp.getStatusLine().getStatusCode());
    assertEquals("a:b", EntityUtils.toString(resp.getEntity()).trim());
}
Also used : GSSName(org.ietf.jgss.GSSName) BasicCredentialsProvider(org.apache.http.impl.client.BasicCredentialsProvider) KerberosTicket(javax.security.auth.kerberos.KerberosTicket) HttpGet(org.apache.http.client.methods.HttpGet) KerberosCredentials(org.apache.http.auth.KerberosCredentials) HttpResponse(org.apache.http.HttpResponse) HttpClientContext(org.apache.http.client.protocol.HttpClientContext) Oid(org.ietf.jgss.Oid) SPNegoSchemeFactory(org.apache.http.impl.auth.SPNegoSchemeFactory) Subject(javax.security.auth.Subject) KrbException(org.apache.kerby.kerberos.kerb.KrbException) IOException(java.io.IOException) URL(java.net.URL) GSSCredential(org.ietf.jgss.GSSCredential) HttpHost(org.apache.http.HttpHost) GSSManager(org.ietf.jgss.GSSManager) HttpClient(org.apache.http.client.HttpClient) Lookup(org.apache.http.config.Lookup) Principal(java.security.Principal) Test(org.junit.Test)

Example 19 with SPNegoSchemeFactory

use of org.apache.http.impl.auth.SPNegoSchemeFactory in project knox by apache.

the class KnoxSession method createClient.

@SuppressForbidden
protected CloseableHttpClient createClient(ClientContext clientContext) throws GeneralSecurityException {
    // SSL
    HostnameVerifier hostnameVerifier = NoopHostnameVerifier.INSTANCE;
    TrustStrategy trustStrategy = null;
    if (clientContext.connection().secure()) {
        hostnameVerifier = SSLConnectionSocketFactory.getDefaultHostnameVerifier();
    } else {
        trustStrategy = TrustSelfSignedStrategy.INSTANCE;
        System.out.println("**************** WARNING ******************\n" + "This is an insecure client instance and may\n" + "leave the interactions subject to a man in\n" + "the middle attack. Please use the login()\n" + "method instead of loginInsecure() for any\n" + "sensitive or production usecases.\n" + "*******************************************");
    }
    KeyStore trustStore = getTrustStore(clientContext);
    SSLContext sslContext = SSLContexts.custom().loadTrustMaterial(trustStore, trustStrategy).build();
    Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create().register("http", PlainConnectionSocketFactory.getSocketFactory()).register("https", new SSLConnectionSocketFactory(sslContext, hostnameVerifier)).build();
    // Pool
    PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(registry);
    connectionManager.setMaxTotal(clientContext.pool().maxTotal());
    connectionManager.setDefaultMaxPerRoute(clientContext.pool().defaultMaxPerRoute());
    ConnectionConfig connectionConfig = ConnectionConfig.custom().setBufferSize(clientContext.connection().bufferSize()).build();
    connectionManager.setDefaultConnectionConfig(connectionConfig);
    SocketConfig socketConfig = SocketConfig.custom().setSoKeepAlive(clientContext.socket().keepalive()).setSoLinger(clientContext.socket().linger()).setSoReuseAddress(clientContext.socket().reuseAddress()).setSoTimeout(clientContext.socket().timeout()).setTcpNoDelay(clientContext.socket().tcpNoDelay()).build();
    connectionManager.setDefaultSocketConfig(socketConfig);
    // Auth
    URI uri = URI.create(clientContext.url());
    host = new HttpHost(uri.getHost(), uri.getPort(), uri.getScheme());
    /* kerberos auth */
    if (clientContext.kerberos().enable()) {
        isKerberos = true;
        /* set up system properties */
        if (!StringUtils.isBlank(clientContext.kerberos().krb5Conf())) {
            System.setProperty("java.security.krb5.conf", clientContext.kerberos().krb5Conf());
        }
        if (!StringUtils.isBlank(clientContext.kerberos().jaasConf())) {
            File f = new File(clientContext.kerberos().jaasConf());
            if (f.exists()) {
                try {
                    jaasConfigURL = f.getCanonicalFile().toURI().toURL();
                    LOG.jaasConfigurationLocation(jaasConfigURL.toExternalForm());
                } catch (IOException e) {
                    LOG.failedToLocateJAASConfiguration(e.getMessage());
                }
            } else {
                LOG.jaasConfigurationDoesNotExist(f.getAbsolutePath());
            }
        }
        // Fall back to the default JAAS config
        if (jaasConfigURL == null) {
            LOG.usingDefaultJAASConfiguration();
            jaasConfigURL = getClass().getResource(DEFAULT_JAAS_FILE);
            LOG.jaasConfigurationLocation(jaasConfigURL.toExternalForm());
        }
        if (clientContext.kerberos().debug()) {
            System.setProperty("sun.security.krb5.debug", "true");
            System.setProperty("sun.security.jgss.debug", "true");
        }
        // (KNOX-2001) Log a warning if the useSubjectCredsOnly restriction is "relaxed"
        String useSubjectCredsOnly = System.getProperty("javax.security.auth.useSubjectCredsOnly");
        if (useSubjectCredsOnly != null && !Boolean.parseBoolean(useSubjectCredsOnly)) {
            LOG.useSubjectCredsOnlyIsFalse();
        }
        final Registry<AuthSchemeProvider> authSchemeRegistry = RegistryBuilder.<AuthSchemeProvider>create().register(AuthSchemes.SPNEGO, new SPNegoSchemeFactory(true)).build();
        return HttpClients.custom().setConnectionManager(connectionManager).setDefaultAuthSchemeRegistry(authSchemeRegistry).setDefaultCredentialsProvider(EMPTY_CREDENTIALS_PROVIDER).build();
    } else {
        AuthCache authCache = new BasicAuthCache();
        BasicScheme authScheme = new BasicScheme();
        authCache.put(host, authScheme);
        context = new BasicHttpContext();
        context.setAttribute(org.apache.http.client.protocol.HttpClientContext.AUTH_CACHE, authCache);
        CredentialsProvider credentialsProvider = null;
        if (clientContext.username() != null && clientContext.password() != null) {
            credentialsProvider = new BasicCredentialsProvider();
            credentialsProvider.setCredentials(new AuthScope(host.getHostName(), host.getPort()), new UsernamePasswordCredentials(clientContext.username(), clientContext.password()));
        }
        return HttpClients.custom().setConnectionManager(connectionManager).setDefaultCredentialsProvider(credentialsProvider).build();
    }
}
Also used : TrustStrategy(org.apache.http.conn.ssl.TrustStrategy) BasicCredentialsProvider(org.apache.http.impl.client.BasicCredentialsProvider) BasicHttpContext(org.apache.http.protocol.BasicHttpContext) BasicAuthCache(org.apache.http.impl.client.BasicAuthCache) SSLConnectionSocketFactory(org.apache.http.conn.ssl.SSLConnectionSocketFactory) URI(java.net.URI) SSLConnectionSocketFactory(org.apache.http.conn.ssl.SSLConnectionSocketFactory) ConnectionSocketFactory(org.apache.http.conn.socket.ConnectionSocketFactory) PlainConnectionSocketFactory(org.apache.http.conn.socket.PlainConnectionSocketFactory) HttpHost(org.apache.http.HttpHost) ConnectionConfig(org.apache.http.config.ConnectionConfig) BasicScheme(org.apache.http.impl.auth.BasicScheme) SocketConfig(org.apache.http.config.SocketConfig) AuthCache(org.apache.http.client.AuthCache) BasicAuthCache(org.apache.http.impl.client.BasicAuthCache) SSLContext(javax.net.ssl.SSLContext) IOException(java.io.IOException) SPNegoSchemeFactory(org.apache.http.impl.auth.SPNegoSchemeFactory) BasicCredentialsProvider(org.apache.http.impl.client.BasicCredentialsProvider) CredentialsProvider(org.apache.http.client.CredentialsProvider) KeyStore(java.security.KeyStore) NoopHostnameVerifier(org.apache.http.conn.ssl.NoopHostnameVerifier) HostnameVerifier(javax.net.ssl.HostnameVerifier) PoolingHttpClientConnectionManager(org.apache.http.impl.conn.PoolingHttpClientConnectionManager) UsernamePasswordCredentials(org.apache.http.auth.UsernamePasswordCredentials) AuthScope(org.apache.http.auth.AuthScope) AuthSchemeProvider(org.apache.http.auth.AuthSchemeProvider) File(java.io.File) SuppressForbidden(de.thetaphi.forbiddenapis.SuppressForbidden)

Aggregations

SPNegoSchemeFactory (org.apache.http.impl.auth.SPNegoSchemeFactory)19 BasicCredentialsProvider (org.apache.http.impl.client.BasicCredentialsProvider)12 AuthSchemeProvider (org.apache.http.auth.AuthSchemeProvider)10 CredentialsProvider (org.apache.http.client.CredentialsProvider)8 HttpHost (org.apache.http.HttpHost)7 Lookup (org.apache.http.config.Lookup)7 Subject (javax.security.auth.Subject)6 KerberosTicket (javax.security.auth.kerberos.KerberosTicket)6 KerberosCredentials (org.apache.http.auth.KerberosCredentials)6 Principal (java.security.Principal)5 AuthScope (org.apache.http.auth.AuthScope)5 Credentials (org.apache.http.auth.Credentials)5 File (java.io.File)4 GSSCredential (org.ietf.jgss.GSSCredential)4 GSSManager (org.ietf.jgss.GSSManager)4 GSSName (org.ietf.jgss.GSSName)4 Oid (org.ietf.jgss.Oid)4 IOException (java.io.IOException)3 Locale (java.util.Locale)3 StringUtils (org.apache.commons.lang.StringUtils)3