Search in sources :

Example 51 with BasicScheme

use of org.apache.http.impl.auth.BasicScheme in project iaf by ibissource.

the class HttpSenderBase method configure.

public void configure() throws ConfigurationException {
    super.configure();
    if (!getMethodType().equals("POST")) {
        if (!isParamsInUrl()) {
            throw new ConfigurationException(getLogPrefix() + "paramsInUrl can only be set to false for methodType POST");
        }
        if (StringUtils.isNotEmpty(getInputMessageParam())) {
            throw new ConfigurationException(getLogPrefix() + "inputMessageParam can only be set for methodType POST");
        }
    }
    Builder requestConfig = RequestConfig.custom();
    requestConfig.setConnectTimeout(getTimeout());
    requestConfig.setConnectionRequestTimeout(getTimeout());
    requestConfig.setSocketTimeout(getTimeout());
    if (paramList != null) {
        paramList.configure();
        if (StringUtils.isNotEmpty(getUrlParam())) {
            urlParameter = paramList.findParameter(getUrlParam());
            addParameterToSkip(urlParameter);
        }
    }
    if (getMaxConnections() <= 0) {
        throw new ConfigurationException(getLogPrefix() + "maxConnections is set to [" + getMaxConnections() + "], which is not enough for adequate operation");
    }
    try {
        if (urlParameter == null) {
            if (StringUtils.isEmpty(getUrl())) {
                throw new ConfigurationException(getLogPrefix() + "url must be specified, either as attribute, or as parameter");
            }
            staticUri = getURI(getUrl());
        }
        URL certificateUrl = null;
        URL truststoreUrl = null;
        if (!StringUtils.isEmpty(getCertificate())) {
            certificateUrl = ClassUtils.getResourceURL(classLoader, getCertificate());
            if (certificateUrl == null) {
                throw new ConfigurationException(getLogPrefix() + "cannot find URL for certificate resource [" + getCertificate() + "]");
            }
            log.info(getLogPrefix() + "resolved certificate-URL to [" + certificateUrl.toString() + "]");
        }
        if (!StringUtils.isEmpty(getTruststore())) {
            truststoreUrl = ClassUtils.getResourceURL(classLoader, getTruststore());
            if (truststoreUrl == null) {
                throw new ConfigurationException(getLogPrefix() + "cannot find URL for truststore resource [" + getTruststore() + "]");
            }
            log.info(getLogPrefix() + "resolved truststore-URL to [" + truststoreUrl.toString() + "]");
        }
        if (certificateUrl != null || truststoreUrl != null || allowSelfSignedCertificates) {
            AuthSSLProtocolSocketFactoryBase socketfactory;
            try {
                CredentialFactory certificateCf = new CredentialFactory(getCertificateAuthAlias(), null, getCertificatePassword());
                CredentialFactory truststoreCf = new CredentialFactory(getTruststoreAuthAlias(), null, getTruststorePassword());
                if (isJdk13Compatibility()) {
                    socketfactory = new AuthSSLProtocolSocketFactoryForJsse10x(certificateUrl, certificateCf.getPassword(), getKeystoreType(), getKeyManagerAlgorithm(), truststoreUrl, truststoreCf.getPassword(), getTruststoreType(), getTrustManagerAlgorithm(), isAllowSelfSignedCertificates(), isVerifyHostname(), isIgnoreCertificateExpiredException());
                } else {
                    socketfactory = new AuthSSLProtocolSocketFactory(certificateUrl, certificateCf.getPassword(), getKeystoreType(), getKeyManagerAlgorithm(), truststoreUrl, truststoreCf.getPassword(), getTruststoreType(), getTrustManagerAlgorithm(), isAllowSelfSignedCertificates(), isVerifyHostname(), isIgnoreCertificateExpiredException());
                }
                if (StringUtils.isNotEmpty(getProtocol())) {
                    socketfactory.setProtocol(getProtocol());
                }
                socketfactory.initSSLContext();
                SSLContext sslContext = (SSLContext) socketfactory.sslContext;
                SSLConnectionSocketFactory socketFactory = new SSLConnectionSocketFactory(sslContext);
                httpClientBuilder.setSSLSocketFactory(socketFactory);
            } catch (Throwable t) {
                throw new ConfigurationException(getLogPrefix() + "cannot create or initialize SocketFactory", t);
            }
        }
        credentials = new CredentialFactory(getAuthAlias(), getUserName(), getPassword());
        CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
        if (!StringUtils.isEmpty(credentials.getUsername())) {
            String uname;
            if (StringUtils.isNotEmpty(getAuthDomain())) {
                uname = getAuthDomain() + "\\" + credentials.getUsername();
            } else {
                uname = credentials.getUsername();
            }
            credentialsProvider.setCredentials(new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT), new UsernamePasswordCredentials(uname, credentials.getPassword()));
        }
        if (StringUtils.isNotEmpty(getProxyHost())) {
            HttpHost proxy = new HttpHost(getProxyHost(), getProxyPort());
            AuthScope scope = new AuthScope(proxy, getProxyRealm(), AuthScope.ANY_SCHEME);
            CredentialFactory pcf = new CredentialFactory(getProxyAuthAlias(), getProxyUserName(), getProxyPassword());
            if (StringUtils.isNotEmpty(pcf.getUsername())) {
                Credentials credentials = new UsernamePasswordCredentials(pcf.getUsername(), pcf.getPassword());
                credentialsProvider.setCredentials(scope, credentials);
            }
            log.trace("setting credentialProvider [" + credentialsProvider.toString() + "]");
            requestConfig.setProxy(proxy);
            requestConfig.setProxyPreferredAuthSchemes(Arrays.asList(AuthSchemes.BASIC));
            AuthCache authCache = httpClientContext.getAuthCache();
            if (authCache == null)
                authCache = new BasicAuthCache();
            authCache.put(proxy, new BasicScheme());
            httpClientContext.setAuthCache(authCache);
            httpClientBuilder.setProxy(proxy);
        }
        httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider);
    } catch (URISyntaxException e) {
        throw new ConfigurationException(getLogPrefix() + "cannot interpret uri [" + getUrl() + "]");
    }
    if (StringUtils.isNotEmpty(getStyleSheetName())) {
        try {
            URL stylesheetURL = ClassUtils.getResourceURL(classLoader, getStyleSheetName());
            if (stylesheetURL == null) {
                throw new ConfigurationException(getLogPrefix() + "cannot find stylesheet [" + getStyleSheetName() + "]");
            }
            transformerPool = TransformerPool.getInstance(stylesheetURL);
        } catch (IOException e) {
            throw new ConfigurationException(getLogPrefix() + "cannot retrieve [" + getStyleSheetName() + "]", e);
        } catch (TransformerConfigurationException te) {
            throw new ConfigurationException(getLogPrefix() + "got error creating transformer from file [" + getStyleSheetName() + "]", te);
        }
    }
    httpClientBuilder.setDefaultRequestConfig(requestConfig.build());
}
Also used : BasicScheme(org.apache.http.impl.auth.BasicScheme) BasicCredentialsProvider(org.apache.http.impl.client.BasicCredentialsProvider) TransformerConfigurationException(javax.xml.transform.TransformerConfigurationException) CredentialFactory(nl.nn.adapterframework.util.CredentialFactory) Builder(org.apache.http.client.config.RequestConfig.Builder) URIBuilder(org.apache.http.client.utils.URIBuilder) HttpClientBuilder(org.apache.http.impl.client.HttpClientBuilder) AuthCache(org.apache.http.client.AuthCache) BasicAuthCache(org.apache.http.impl.client.BasicAuthCache) SSLContext(javax.net.ssl.SSLContext) BasicCredentialsProvider(org.apache.http.impl.client.BasicCredentialsProvider) CredentialsProvider(org.apache.http.client.CredentialsProvider) BasicAuthCache(org.apache.http.impl.client.BasicAuthCache) URISyntaxException(java.net.URISyntaxException) IOException(java.io.IOException) SSLConnectionSocketFactory(org.apache.http.conn.ssl.SSLConnectionSocketFactory) URL(java.net.URL) UsernamePasswordCredentials(org.apache.http.auth.UsernamePasswordCredentials) TransformerConfigurationException(javax.xml.transform.TransformerConfigurationException) ConfigurationException(nl.nn.adapterframework.configuration.ConfigurationException) HttpHost(org.apache.http.HttpHost) AuthScope(org.apache.http.auth.AuthScope) Credentials(org.apache.http.auth.Credentials) UsernamePasswordCredentials(org.apache.http.auth.UsernamePasswordCredentials)

Example 52 with BasicScheme

use of org.apache.http.impl.auth.BasicScheme in project camel by apache.

the class HttpProducer method executeMethod.

/**
     * Strategy when executing the method (calling the remote server).
     *
     * @param httpRequest the http Request to execute
     * @return the response
     * @throws IOException can be thrown
     */
protected HttpResponse executeMethod(HttpUriRequest httpRequest) throws IOException {
    HttpContext localContext = new BasicHttpContext();
    if (getEndpoint().isAuthenticationPreemptive()) {
        BasicScheme basicAuth = new BasicScheme();
        localContext.setAttribute("preemptive-auth", basicAuth);
    }
    if (httpContext != null) {
        localContext = new BasicHttpContext(httpContext);
    }
    return httpClient.execute(httpRequest, localContext);
}
Also used : BasicScheme(org.apache.http.impl.auth.BasicScheme) BasicHttpContext(org.apache.http.protocol.BasicHttpContext) BasicHttpContext(org.apache.http.protocol.BasicHttpContext) HttpContext(org.apache.http.protocol.HttpContext)

Example 53 with BasicScheme

use of org.apache.http.impl.auth.BasicScheme in project tmdm-studio-se by Talend.

the class HttpClientUtil method authenticate.

private static void authenticate(String username, String password, HttpUriRequest request, HttpContext preemptiveContext) {
    try {
        BasicScheme basicScheme = new BasicScheme();
        Header authenticateHeader = basicScheme.authenticate(new UsernamePasswordCredentials(username, password), request, preemptiveContext);
        request.addHeader(authenticateHeader);
    } catch (AuthenticationException e) {
        log.error(e.getMessage(), e);
    }
}
Also used : BasicScheme(org.apache.http.impl.auth.BasicScheme) Header(org.apache.http.Header) AuthenticationException(org.apache.http.auth.AuthenticationException) UsernamePasswordCredentials(org.apache.http.auth.UsernamePasswordCredentials)

Example 54 with BasicScheme

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

the class Hadoop method createClient.

private 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();
    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());
    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()));
        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);
    }
    return HttpClients.custom().setConnectionManager(connectionManager).setDefaultCredentialsProvider(credentialsProvider).build();
}
Also used : BasicScheme(org.apache.http.impl.auth.BasicScheme) TrustStrategy(org.apache.http.conn.ssl.TrustStrategy) BasicCredentialsProvider(org.apache.http.impl.client.BasicCredentialsProvider) SocketConfig(org.apache.http.config.SocketConfig) BasicHttpContext(org.apache.http.protocol.BasicHttpContext) AuthCache(org.apache.http.client.AuthCache) BasicAuthCache(org.apache.http.impl.client.BasicAuthCache) SSLContext(javax.net.ssl.SSLContext) BasicCredentialsProvider(org.apache.http.impl.client.BasicCredentialsProvider) CredentialsProvider(org.apache.http.client.CredentialsProvider) BasicAuthCache(org.apache.http.impl.client.BasicAuthCache) KeyStore(java.security.KeyStore) SSLConnectionSocketFactory(org.apache.http.conn.ssl.SSLConnectionSocketFactory) URI(java.net.URI) 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) 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) AuthScope(org.apache.http.auth.AuthScope) ConnectionConfig(org.apache.http.config.ConnectionConfig)

Example 55 with BasicScheme

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

the class GatewayBasicFuncTest method oozieSubmitJob.

/* GET /oozie/v1/admin/status
    HTTP/1.1 200 OK
    Content-Type: application/json;charset=UTF-8
    Content-Length: 23
    Server: Apache-Coyote/1.1
    Date: Thu, 14 Feb 2013 15:49:16 GMT
    See: oozie-admin-status.json
   */
/* PUT /oozie/v1/admin/status?safemode=true
  TODO
  */
/* GET /oozie/v1/admin/os-env
    HTTP/1.1 200 OK
    Content-Type: application/json;charset=UTF-8
    Content-Length: 2039
    Server: Apache-Coyote/1.1
    Date: Thu, 14 Feb 2013 15:51:56 GMT
    See: oozie-admin-os-env.json
   */
/* GET /oozie/v1/admin/java-sys-properties
    HTTP/1.1 200 OK
    Content-Type: application/json;charset=UTF-8
    Content-Length: 3673
    Server: Apache-Coyote/1.1
    Date: Thu, 14 Feb 2013 15:53:00 GMT
    See: oozie-admin-java-sys-properties.json
  */
/* GET /oozie/v1/admin/configuration
    HTTP/1.1 200 OK
    Transfer-Encoding: Identity
    Content-Type: application/json;charset=UTF-8
    Server: Apache-Coyote/1.1
    Date: Thu, 14 Feb 2013 15:53:31 GMT
    See: oozie-admin-configuration.json
  */
/* GET /oozie/v1/admin/instrumentation
    HTTP/1.1 200 OK
    Transfer-Encoding: Identity
    Content-Type: application/json;charset=UTF-8
    Server: Apache-Coyote/1.1
    Date: Thu, 14 Feb 2013 15:55:43 GMT
    See: oozie-admin-instrumentation.json
  */
/* GET /oozie/v1/admin/build-version
    HTTP/1.1 200 OK
    Content-Type: application/json;charset=UTF-8
    Content-Length: 27
    Server: Apache-Coyote/1.1
    Date: Thu, 14 Feb 2013 16:08:31 GMT
    See: oozie-admin-build-version.json
  */
/* POST /oozie/v1/jobs (request XML; contains URL, response JSON)
    Content-Type: application/json;charset=UTF-8
    Content-Length: 45
    Server: Apache-Coyote/1.1
    Date: Thu, 14 Feb 2013 18:10:52 GMT
  */
private String oozieSubmitJob(String user, String password, String request, int status) throws IOException, URISyntaxException {
    driver.getMock("OOZIE").expect().method("POST").pathInfo("/v1/jobs").respond().status(HttpStatus.SC_CREATED).content(driver.getResourceBytes("oozie-jobs-submit-response.json")).contentType("application/json");
    // System.out.println( "REQUEST LENGTH = " + request.length() );
    URL url = new URL(driver.getUrl("OOZIE") + "/v1/jobs?action=start" + (driver.isUseGateway() ? "" : "&user.name=" + user));
    HttpHost targetHost = new HttpHost(url.getHost(), url.getPort(), url.getProtocol());
    HttpClientBuilder builder = HttpClientBuilder.create();
    CloseableHttpClient client = builder.build();
    HttpClientContext context = HttpClientContext.create();
    CredentialsProvider credsProvider = new BasicCredentialsProvider();
    credsProvider.setCredentials(new AuthScope(targetHost), new UsernamePasswordCredentials(user, password));
    context.setCredentialsProvider(credsProvider);
    // Create AuthCache instance
    AuthCache authCache = new BasicAuthCache();
    // Generate BASIC scheme object and add it to the local auth cache
    BasicScheme basicAuth = new BasicScheme();
    authCache.put(targetHost, basicAuth);
    // Add AuthCache to the execution context
    context.setAuthCache(authCache);
    HttpPost post = new HttpPost(url.toURI());
    // post.getParams().setParameter( "action", "start" );
    StringEntity entity = new StringEntity(request, org.apache.http.entity.ContentType.create("application/xml", "UTF-8"));
    post.setEntity(entity);
    post.setHeader("X-XSRF-Header", "ksdjfhdsjkfhds");
    HttpResponse response = client.execute(targetHost, post, context);
    assertThat(response.getStatusLine().getStatusCode(), Matchers.is(status));
    String json = EntityUtils.toString(response.getEntity());
    // String json = given()
    // .log().all()
    // .auth().preemptive().basic( user, password )
    // .queryParam( "action", "start" )
    // .contentType( "application/xml;charset=UTF-8" )
    // .content( request )
    // .then()
    // .log().all()
    // .statusCode( status )
    // .when().post( getUrl( "OOZIE" ) + "/v1/jobs" + ( isUseGateway() ? "" : "?user.name=" + user ) ).asString();
    // System.out.println( "JSON=" + json );
    String id = JsonPath.from(json).getString("id");
    return id;
}
Also used : CloseableHttpClient(org.apache.http.impl.client.CloseableHttpClient) BasicScheme(org.apache.http.impl.auth.BasicScheme) HttpPost(org.apache.http.client.methods.HttpPost) BasicCredentialsProvider(org.apache.http.impl.client.BasicCredentialsProvider) AuthCache(org.apache.http.client.AuthCache) BasicAuthCache(org.apache.http.impl.client.BasicAuthCache) HttpResponse(org.apache.http.HttpResponse) HttpClientContext(org.apache.http.client.protocol.HttpClientContext) HttpClientBuilder(org.apache.http.impl.client.HttpClientBuilder) BasicCredentialsProvider(org.apache.http.impl.client.BasicCredentialsProvider) CredentialsProvider(org.apache.http.client.CredentialsProvider) BasicAuthCache(org.apache.http.impl.client.BasicAuthCache) IsEmptyString.isEmptyString(org.hamcrest.text.IsEmptyString.isEmptyString) Matchers.containsString(org.hamcrest.Matchers.containsString) URL(java.net.URL) UsernamePasswordCredentials(org.apache.http.auth.UsernamePasswordCredentials) StringEntity(org.apache.http.entity.StringEntity) HttpHost(org.apache.http.HttpHost) AuthScope(org.apache.http.auth.AuthScope)

Aggregations

BasicScheme (org.apache.http.impl.auth.BasicScheme)82 UsernamePasswordCredentials (org.apache.http.auth.UsernamePasswordCredentials)57 CredentialsProvider (org.apache.http.client.CredentialsProvider)48 BasicAuthCache (org.apache.http.impl.client.BasicAuthCache)47 AuthCache (org.apache.http.client.AuthCache)46 BasicCredentialsProvider (org.apache.http.impl.client.BasicCredentialsProvider)46 HttpHost (org.apache.http.HttpHost)45 AuthScope (org.apache.http.auth.AuthScope)38 HttpClientContext (org.apache.http.client.protocol.HttpClientContext)32 CloseableHttpClient (org.apache.http.impl.client.CloseableHttpClient)25 CloseableHttpResponse (org.apache.http.client.methods.CloseableHttpResponse)24 HttpGet (org.apache.http.client.methods.HttpGet)23 URI (java.net.URI)20 Test (org.junit.Test)18 IOException (java.io.IOException)13 Credentials (org.apache.http.auth.Credentials)13 HttpResponse (org.apache.http.HttpResponse)9 HttpPost (org.apache.http.client.methods.HttpPost)9 BasicHttpContext (org.apache.http.protocol.BasicHttpContext)9 Header (org.apache.http.Header)8