Search in sources :

Example 51 with NTCredentials

use of org.apache.http.auth.NTCredentials in project jmeter-plugins-manager by undera.

the class JARSourceHTTP method getHTTPClient.

private AbstractHttpClient getHTTPClient() {
    AbstractHttpClient client = new DefaultHttpClient();
    String proxyHost = System.getProperty("https.proxyHost", "");
    if (!proxyHost.isEmpty()) {
        int proxyPort = Integer.parseInt(System.getProperty("https.proxyPort", "-1"));
        log.info("Using proxy " + proxyHost + ":" + proxyPort);
        HttpParams params = client.getParams();
        HttpHost proxy = new HttpHost(proxyHost, proxyPort);
        params.setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
        String proxyUser = System.getProperty(JMeter.HTTP_PROXY_USER, org.apache.jmeter.util.JMeterUtils.getProperty(JMeter.HTTP_PROXY_USER));
        if (proxyUser != null) {
            log.info("Using authenticated proxy with username: " + proxyUser);
            String proxyPass = System.getProperty(JMeter.HTTP_PROXY_PASS, JMeterUtils.getProperty(JMeter.HTTP_PROXY_PASS));
            String localHost;
            try {
                localHost = InetAddress.getLocalHost().getCanonicalHostName();
            } catch (Throwable e) {
                log.error("Failed to get local host name, defaulting to 'localhost'", e);
                localHost = "localhost";
            }
            AuthScope authscope = new AuthScope(proxyHost, proxyPort);
            String proxyDomain = JMeterUtils.getPropDefault("http.proxyDomain", "");
            NTCredentials credentials = new NTCredentials(proxyUser, proxyPass, localHost, proxyDomain);
            client.getCredentialsProvider().setCredentials(authscope, credentials);
        }
    }
    client.setHttpRequestRetryHandler(new DefaultHttpRequestRetryHandler(RETRY_COUNT, true));
    return client;
}
Also used : AbstractHttpClient(org.apache.http.impl.client.AbstractHttpClient) HttpParams(org.apache.http.params.HttpParams) HttpHost(org.apache.http.HttpHost) AuthScope(org.apache.http.auth.AuthScope) DefaultHttpRequestRetryHandler(org.apache.http.impl.client.DefaultHttpRequestRetryHandler) DefaultHttpClient(org.apache.http.impl.client.DefaultHttpClient) NTCredentials(org.apache.http.auth.NTCredentials)

Example 52 with NTCredentials

use of org.apache.http.auth.NTCredentials in project jmeter by apache.

the class HTTPHC4Impl method setupClient.

private MutableTriple<CloseableHttpClient, AuthState, PoolingHttpClientConnectionManager> setupClient(HttpClientKey key, JMeterVariables jMeterVariables, HttpClientContext clientContext) throws GeneralSecurityException {
    Map<HttpClientKey, MutableTriple<CloseableHttpClient, AuthState, PoolingHttpClientConnectionManager>> mapHttpClientPerHttpClientKey = HTTPCLIENTS_CACHE_PER_THREAD_AND_HTTPCLIENTKEY.get();
    clientContext.setAttribute(CONTEXT_ATTRIBUTE_CLIENT_KEY, key);
    CloseableHttpClient httpClient = null;
    MutableTriple<CloseableHttpClient, AuthState, PoolingHttpClientConnectionManager> triple = null;
    boolean concurrentDwn = this.testElement.isConcurrentDwn();
    Map<String, Object> samplerContext = JMeterContextService.getContext().getSamplerContext();
    if (concurrentDwn) {
        triple = (MutableTriple<CloseableHttpClient, AuthState, PoolingHttpClientConnectionManager>) samplerContext.get(CONTEXT_ATTRIBUTE_PARENT_SAMPLE_CLIENT_STATE);
    }
    if (triple == null) {
        triple = mapHttpClientPerHttpClientKey.get(key);
    }
    if (triple != null) {
        httpClient = triple.getLeft();
    }
    setupProxyAuthState(triple, clientContext);
    resetStateIfNeeded(triple, jMeterVariables, clientContext, mapHttpClientPerHttpClientKey);
    if (httpClient == null) {
        // One-time init for this client
        DnsResolver resolver = this.testElement.getDNSResolver();
        if (resolver == null) {
            resolver = SystemDefaultDnsResolver.INSTANCE;
        }
        Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create().register("https", new LazyLayeredConnectionSocketFactory()).register("http", CONNECTION_SOCKET_FACTORY).build();
        // Modern browsers use more connections per host than the current httpclient default (2)
        // when using parallel download the httpclient and connection manager are shared by the downloads threads
        // to be realistic JMeter must set an higher value to DefaultMaxPerRoute
        PoolingHttpClientConnectionManager pHCCM = new PoolingHttpClientConnectionManager(new JMeterDefaultHttpClientConnectionOperator(registry, null, resolver), null, TIME_TO_LIVE, TimeUnit.MILLISECONDS);
        pHCCM.setValidateAfterInactivity(VALIDITY_AFTER_INACTIVITY_TIMEOUT);
        if (concurrentDwn) {
            try {
                int maxConcurrentDownloads = Integer.parseInt(this.testElement.getConcurrentPool());
                pHCCM.setDefaultMaxPerRoute(Math.max(maxConcurrentDownloads, pHCCM.getDefaultMaxPerRoute()));
            } catch (NumberFormatException nfe) {
            // no need to log -> will be done by the sampler
            }
        }
        CookieSpecProvider cookieSpecProvider = new IgnoreSpecProvider();
        Lookup<CookieSpecProvider> cookieSpecRegistry = RegistryBuilder.<CookieSpecProvider>create().register(CookieSpecs.IGNORE_COOKIES, cookieSpecProvider).build();
        HttpClientBuilder builder = HttpClients.custom().setConnectionManager(pHCCM).setSchemePortResolver(new DefaultSchemePortResolver()).setDnsResolver(resolver).setRequestExecutor(REQUEST_EXECUTOR).setSSLSocketFactory(new LazyLayeredConnectionSocketFactory()).setDefaultCookieSpecRegistry(cookieSpecRegistry).setDefaultSocketConfig(SocketConfig.DEFAULT).setRedirectStrategy(new LaxRedirectStrategy()).setConnectionTimeToLive(TIME_TO_LIVE, TimeUnit.MILLISECONDS).setRetryHandler(new StandardHttpRequestRetryHandler(RETRY_COUNT, REQUEST_SENT_RETRY_ENABLED)).setConnectionReuseStrategy(DefaultClientConnectionReuseStrategy.INSTANCE).setProxyAuthenticationStrategy(getProxyAuthStrategy());
        if (DISABLE_DEFAULT_UA) {
            builder.disableDefaultUserAgent();
        }
        Lookup<AuthSchemeProvider> authSchemeRegistry = RegistryBuilder.<AuthSchemeProvider>create().register(AuthSchemes.BASIC, new BasicSchemeFactory()).register(AuthSchemes.DIGEST, new DigestSchemeFactory()).register(AuthSchemes.NTLM, new NTLMSchemeFactory()).register(AuthSchemes.SPNEGO, new DynamicSPNegoSchemeFactory(AuthManager.STRIP_PORT, AuthManager.USE_CANONICAL_HOST_NAME)).register(AuthSchemes.KERBEROS, new DynamicKerberosSchemeFactory(AuthManager.STRIP_PORT, AuthManager.USE_CANONICAL_HOST_NAME)).build();
        builder.setDefaultAuthSchemeRegistry(authSchemeRegistry);
        if (IDLE_TIMEOUT > 0) {
            builder.setKeepAliveStrategy(IDLE_STRATEGY);
        }
        // Set up proxy details
        AuthScope proxyAuthScope = null;
        NTCredentials proxyCredentials = null;
        if (key.hasProxy) {
            HttpHost proxy = new HttpHost(key.proxyHost, key.proxyPort, key.proxyScheme);
            builder.setProxy(proxy);
            CredentialsProvider credsProvider = new BasicCredentialsProvider();
            if (!key.proxyUser.isEmpty()) {
                proxyAuthScope = new AuthScope(key.proxyHost, key.proxyPort);
                proxyCredentials = new NTCredentials(key.proxyUser, key.proxyPass, LOCALHOST, PROXY_DOMAIN);
                credsProvider.setCredentials(proxyAuthScope, proxyCredentials);
            }
            builder.setDefaultCredentialsProvider(credsProvider);
        }
        builder.disableContentCompression().addInterceptorLast(RESPONSE_CONTENT_ENCODING);
        if (BASIC_AUTH_PREEMPTIVE) {
            builder.addInterceptorFirst(PREEMPTIVE_AUTH_INTERCEPTOR);
        } else {
            builder.setDefaultCredentialsProvider(new ManagedCredentialsProvider(getAuthManager(), proxyAuthScope, proxyCredentials));
        }
        httpClient = builder.build();
        if (log.isDebugEnabled()) {
            log.debug("Created new HttpClient: @{} {}", System.identityHashCode(httpClient), key);
        }
        triple = MutableTriple.of(httpClient, null, pHCCM);
        // save the agent for next time round
        mapHttpClientPerHttpClientKey.put(key, triple);
    } else {
        if (log.isDebugEnabled()) {
            log.debug("Reusing the HttpClient: @{} {}", System.identityHashCode(httpClient), key);
        }
    }
    if (concurrentDwn) {
        samplerContext.put(CONTEXT_ATTRIBUTE_PARENT_SAMPLE_CLIENT_STATE, triple);
    }
    return triple;
}
Also used : BasicCredentialsProvider(org.apache.http.impl.client.BasicCredentialsProvider) BasicSchemeFactory(org.apache.http.impl.auth.BasicSchemeFactory) HttpClientBuilder(org.apache.http.impl.client.HttpClientBuilder) NTCredentials(org.apache.http.auth.NTCredentials) ConnectionSocketFactory(org.apache.http.conn.socket.ConnectionSocketFactory) LazyLayeredConnectionSocketFactory(org.apache.jmeter.protocol.http.sampler.hc.LazyLayeredConnectionSocketFactory) SlowHCPlainConnectionSocketFactory(org.apache.jmeter.protocol.http.util.SlowHCPlainConnectionSocketFactory) PlainConnectionSocketFactory(org.apache.http.conn.socket.PlainConnectionSocketFactory) IgnoreSpecProvider(org.apache.http.impl.cookie.IgnoreSpecProvider) HttpHost(org.apache.http.HttpHost) DigestSchemeFactory(org.apache.http.impl.auth.DigestSchemeFactory) LaxRedirectStrategy(org.apache.http.impl.client.LaxRedirectStrategy) MutableTriple(org.apache.commons.lang3.tuple.MutableTriple) DynamicSPNegoSchemeFactory(org.apache.jmeter.protocol.http.control.DynamicSPNegoSchemeFactory) CloseableHttpClient(org.apache.http.impl.client.CloseableHttpClient) SystemDefaultDnsResolver(org.apache.http.impl.conn.SystemDefaultDnsResolver) DnsResolver(org.apache.http.conn.DnsResolver) LazyLayeredConnectionSocketFactory(org.apache.jmeter.protocol.http.sampler.hc.LazyLayeredConnectionSocketFactory) DynamicKerberosSchemeFactory(org.apache.jmeter.protocol.http.control.DynamicKerberosSchemeFactory) CredentialsProvider(org.apache.http.client.CredentialsProvider) BasicCredentialsProvider(org.apache.http.impl.client.BasicCredentialsProvider) PoolingHttpClientConnectionManager(org.apache.http.impl.conn.PoolingHttpClientConnectionManager) StandardHttpRequestRetryHandler(org.apache.http.impl.client.StandardHttpRequestRetryHandler) AuthState(org.apache.http.auth.AuthState) DefaultSchemePortResolver(org.apache.http.impl.conn.DefaultSchemePortResolver) AuthScope(org.apache.http.auth.AuthScope) CookieSpecProvider(org.apache.http.cookie.CookieSpecProvider) AuthSchemeProvider(org.apache.http.auth.AuthSchemeProvider) NTLMSchemeFactory(org.apache.http.impl.auth.NTLMSchemeFactory)

Example 53 with NTCredentials

use of org.apache.http.auth.NTCredentials in project dependency-track by DependencyTrack.

the class ManagedHttpClientFactory method newManagedHttpClient.

/**
 * Factory method that create a PooledHttpClient object. This method will attempt to use
 * proxy settings defined in application.properties first. If they are not set,
 * this method will attempt to use proxy settings from the environment by looking
 * for 'https_proxy', 'http_proxy' and 'no_proxy'.
 * @return a PooledHttpClient object with optional proxy settings
 */
public static ManagedHttpClient newManagedHttpClient() {
    PoolingHttpClientConnectionManager connectionManager = null;
    final RequestConfig config = RequestConfig.custom().setConnectTimeout(TIMEOUT_CONNECTION * 1000).setConnectionRequestTimeout(TIMEOUT_POOL * 1000).setSocketTimeout(TIMEOUT_SOCKET * 1000).build();
    final HttpClientBuilder clientBuilder = HttpClientBuilder.create().setDefaultRequestConfig(config);
    final CredentialsProvider credsProvider = new BasicCredentialsProvider();
    clientBuilder.useSystemProperties();
    final ProxyInfo proxyInfo = createProxyInfo();
    if (proxyInfo != null) {
        HttpRoutePlanner routePlanner = new DefaultProxyRoutePlanner(new HttpHost(proxyInfo.host, proxyInfo.port)) {

            @Override
            public HttpRoute determineRoute(final HttpHost host, final HttpRequest request, final HttpContext context) throws HttpException {
                if (isProxy(proxyInfo.noProxy, host)) {
                    return super.determineRoute(host, request, context);
                }
                return new HttpRoute(host);
            }
        };
        clientBuilder.setRoutePlanner(routePlanner);
        if (StringUtils.isNotBlank(proxyInfo.username) && StringUtils.isNotBlank(proxyInfo.password)) {
            if (proxyInfo.domain != null) {
                credsProvider.setCredentials(AuthScope.ANY, new NTCredentials(proxyInfo.username, proxyInfo.password, proxyInfo.domain, null));
            } else {
                credsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(proxyInfo.username, proxyInfo.password));
            }
        }
    }
    // When a proxy is enabled, turn off certificate chain of trust validation and hostname verification
    if (proxyInfo != null && proxyInfo.noProxy == null) {
        try {
            final SSLContext sslContext = SSLContextBuilder.create().loadTrustMaterial(new TrustAllStrategy()).build();
            final Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create().register("http", PlainConnectionSocketFactory.INSTANCE).register("https", new SSLConnectionSocketFactory(sslContext, NoopHostnameVerifier.INSTANCE)).build();
            connectionManager = new PoolingHttpClientConnectionManager(registry);
            connectionManager.setMaxTotal(200);
            connectionManager.setDefaultMaxPerRoute(20);
            clientBuilder.setConnectionManager(connectionManager);
            clientBuilder.setConnectionManagerShared(true);
        } catch (KeyManagementException | KeyStoreException | NoSuchAlgorithmException e) {
            LOGGER.warn("An error occurred while configuring proxy", e);
        }
    } else {
        connectionManager = new PoolingHttpClientConnectionManager();
        connectionManager.setMaxTotal(200);
        connectionManager.setDefaultMaxPerRoute(20);
        clientBuilder.setConnectionManager(connectionManager);
    }
    clientBuilder.setDefaultCredentialsProvider(credsProvider);
    clientBuilder.setProxyAuthenticationStrategy(new ProxyAuthenticationStrategy());
    final Lookup<AuthSchemeProvider> authProviders = RegistryBuilder.<AuthSchemeProvider>create().register(AuthSchemes.BASIC, new BasicSchemeFactory()).register(AuthSchemes.DIGEST, new DigestSchemeFactory()).register(AuthSchemes.NTLM, new NTLMSchemeFactory()).build();
    clientBuilder.setDefaultAuthSchemeRegistry(authProviders);
    clientBuilder.disableCookieManagement();
    clientBuilder.setRedirectStrategy(LaxRedirectStrategy.INSTANCE);
    return new ManagedHttpClient(clientBuilder.build(), connectionManager);
}
Also used : BasicCredentialsProvider(org.apache.http.impl.client.BasicCredentialsProvider) BasicSchemeFactory(org.apache.http.impl.auth.BasicSchemeFactory) DefaultProxyRoutePlanner(org.apache.http.impl.conn.DefaultProxyRoutePlanner) HttpClientBuilder(org.apache.http.impl.client.HttpClientBuilder) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) SSLConnectionSocketFactory(org.apache.http.conn.ssl.SSLConnectionSocketFactory) KeyManagementException(java.security.KeyManagementException) NTCredentials(org.apache.http.auth.NTCredentials) PlainConnectionSocketFactory(org.apache.http.conn.socket.PlainConnectionSocketFactory) SSLConnectionSocketFactory(org.apache.http.conn.ssl.SSLConnectionSocketFactory) ConnectionSocketFactory(org.apache.http.conn.socket.ConnectionSocketFactory) HttpRoutePlanner(org.apache.http.conn.routing.HttpRoutePlanner) HttpHost(org.apache.http.HttpHost) DigestSchemeFactory(org.apache.http.impl.auth.DigestSchemeFactory) ProxyAuthenticationStrategy(org.apache.http.impl.client.ProxyAuthenticationStrategy) HttpRequest(org.apache.http.HttpRequest) RequestConfig(org.apache.http.client.config.RequestConfig) HttpContext(org.apache.http.protocol.HttpContext) BasicCredentialsProvider(org.apache.http.impl.client.BasicCredentialsProvider) CredentialsProvider(org.apache.http.client.CredentialsProvider) SSLContext(javax.net.ssl.SSLContext) KeyStoreException(java.security.KeyStoreException) PoolingHttpClientConnectionManager(org.apache.http.impl.conn.PoolingHttpClientConnectionManager) UsernamePasswordCredentials(org.apache.http.auth.UsernamePasswordCredentials) HttpRoute(org.apache.http.conn.routing.HttpRoute) AuthSchemeProvider(org.apache.http.auth.AuthSchemeProvider) NTLMSchemeFactory(org.apache.http.impl.auth.NTLMSchemeFactory) TrustAllStrategy(org.apache.http.conn.ssl.TrustAllStrategy)

Example 54 with NTCredentials

use of org.apache.http.auth.NTCredentials in project cyberduck by iterate-ch.

the class DAVSession method login.

@Override
public void login(final Proxy proxy, final LoginCallback prompt, final CancelCallback cancel) throws BackgroundException {
    final CredentialsProvider provider = new BasicCredentialsProvider();
    if (preferences.getBoolean("webdav.ntlm.windows.authentication.enable") && WinHttpClients.isWinAuthAvailable()) {
        provider.setCredentials(new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT, AuthScope.ANY_REALM, AuthSchemes.NTLM), new WindowsCredentialsProvider(new BasicCredentialsProvider()).getCredentials(new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT, AuthScope.ANY_REALM, AuthSchemes.NTLM)));
        provider.setCredentials(new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT, AuthScope.ANY_REALM, AuthSchemes.SPNEGO), new WindowsCredentialsProvider(new SystemDefaultCredentialsProvider()).getCredentials(new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT, AuthScope.ANY_REALM, AuthSchemes.SPNEGO)));
    } else {
        provider.setCredentials(new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT, AuthScope.ANY_REALM, AuthSchemes.NTLM), new NTCredentials(host.getCredentials().getUsername(), host.getCredentials().getPassword(), preferences.getProperty("webdav.ntlm.workstation"), preferences.getProperty("webdav.ntlm.domain")));
        provider.setCredentials(new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT, AuthScope.ANY_REALM, AuthSchemes.SPNEGO), new NTCredentials(host.getCredentials().getUsername(), host.getCredentials().getPassword(), preferences.getProperty("webdav.ntlm.workstation"), preferences.getProperty("webdav.ntlm.domain")));
    }
    provider.setCredentials(new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT, AuthScope.ANY_REALM, AuthSchemes.BASIC), new UsernamePasswordCredentials(host.getCredentials().getUsername(), host.getCredentials().getPassword()));
    provider.setCredentials(new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT, AuthScope.ANY_REALM, AuthSchemes.DIGEST), new UsernamePasswordCredentials(host.getCredentials().getUsername(), host.getCredentials().getPassword()));
    provider.setCredentials(new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT, AuthScope.ANY_REALM, AuthSchemes.KERBEROS), new UsernamePasswordCredentials(host.getCredentials().getUsername(), host.getCredentials().getPassword()));
    client.setCredentials(provider);
    if (preferences.getBoolean("webdav.basic.preemptive")) {
        switch(proxy.getType()) {
            case DIRECT:
            case SOCKS:
                // Enable preemptive authentication. See HttpState#setAuthenticationPreemptive
                client.enablePreemptiveAuthentication(host.getHostname(), host.getPort(), host.getPort(), Charset.forName(preferences.getProperty("http.credentials.charset")));
                break;
            default:
                client.disablePreemptiveAuthentication();
        }
    } else {
        client.disablePreemptiveAuthentication();
    }
    if (host.getCredentials().isPassed()) {
        log.warn(String.format("Skip verifying credentials with previous successful authentication event for %s", this));
        return;
    }
    try {
        final Path home = new DelegatingHomeFeature(new WorkdirHomeFeature(host), new DefaultPathHomeFeature(host)).find();
        final HttpHead head = new HttpHead(new DAVPathEncoder().encode(home));
        try {
            client.execute(head, new MicrosoftIISFeaturesResponseHandler());
        } catch (SardineException e) {
            switch(e.getStatusCode()) {
                case HttpStatus.SC_NOT_FOUND:
                    log.warn(String.format("Ignore failure %s", e));
                    break;
                case HttpStatus.SC_NOT_IMPLEMENTED:
                case HttpStatus.SC_FORBIDDEN:
                case HttpStatus.SC_UNSUPPORTED_MEDIA_TYPE:
                case HttpStatus.SC_METHOD_NOT_ALLOWED:
                    log.warn(String.format("Failed HEAD request to %s with %s. Retry with PROPFIND.", host, e.getResponsePhrase()));
                    cancel.verify();
                    // Possibly only HEAD requests are not allowed
                    list.list(home, new DisabledListProgressListener() {

                        @Override
                        public void chunk(final Path parent, final AttributedList<Path> list) throws ListCanceledException {
                            try {
                                cancel.verify();
                            } catch (ConnectionCanceledException e) {
                                throw new ListCanceledException(list, e);
                            }
                        }
                    });
                    break;
                case HttpStatus.SC_BAD_REQUEST:
                    if (preferences.getBoolean("webdav.basic.preemptive")) {
                        log.warn(String.format("Disable preemptive authentication for %s due to failure %s", host, e.getResponsePhrase()));
                        cancel.verify();
                        client.disablePreemptiveAuthentication();
                        client.execute(head, new MicrosoftIISFeaturesResponseHandler());
                    } else {
                        throw new DAVExceptionMappingService().map(e);
                    }
                    break;
                default:
                    throw new DAVExceptionMappingService().map(e);
            }
        }
    } catch (SardineException e) {
        throw new DAVExceptionMappingService().map(e);
    } catch (IOException e) {
        throw new HttpExceptionMappingService().map(e);
    }
}
Also used : Path(ch.cyberduck.core.Path) BasicCredentialsProvider(org.apache.http.impl.client.BasicCredentialsProvider) DelegatingHomeFeature(ch.cyberduck.core.shared.DelegatingHomeFeature) DisabledListProgressListener(ch.cyberduck.core.DisabledListProgressListener) ConnectionCanceledException(ch.cyberduck.core.exception.ConnectionCanceledException) DefaultPathHomeFeature(ch.cyberduck.core.shared.DefaultPathHomeFeature) WindowsCredentialsProvider(org.apache.http.impl.auth.win.WindowsCredentialsProvider) BasicCredentialsProvider(org.apache.http.impl.client.BasicCredentialsProvider) CredentialsProvider(org.apache.http.client.CredentialsProvider) SystemDefaultCredentialsProvider(org.apache.http.impl.client.SystemDefaultCredentialsProvider) IOException(java.io.IOException) WindowsCredentialsProvider(org.apache.http.impl.auth.win.WindowsCredentialsProvider) HttpHead(org.apache.http.client.methods.HttpHead) NTCredentials(org.apache.http.auth.NTCredentials) UsernamePasswordCredentials(org.apache.http.auth.UsernamePasswordCredentials) SardineException(com.github.sardine.impl.SardineException) HttpExceptionMappingService(ch.cyberduck.core.http.HttpExceptionMappingService) AttributedList(ch.cyberduck.core.AttributedList) AuthScope(org.apache.http.auth.AuthScope) SystemDefaultCredentialsProvider(org.apache.http.impl.client.SystemDefaultCredentialsProvider) WorkdirHomeFeature(ch.cyberduck.core.shared.WorkdirHomeFeature) ListCanceledException(ch.cyberduck.core.exception.ListCanceledException)

Example 55 with NTCredentials

use of org.apache.http.auth.NTCredentials in project laverca by laverca.

the class ComponentsHTTPSender method addContextInfo.

/**
 * Extracts info from message context.
 *
 * @param method Post method
 * @param httpClient The client used for posting
 * @param httpContext
 * @param rcb
 * @param msgContext the message context
 * @param tmpURL the url to post to.
 * @throws AxisFault
 */
private void addContextInfo(final HttpPost method, final LavercaHttpClient httpClient, final HttpClientContext httpContext, final RequestConfig.Builder rcb, final MessageContext msgContext, final URL tmpURL) throws AxisFault {
    if (msgContext.getTimeout() != 0) {
        // optionally set a timeout for response waits
        rcb.setSocketTimeout(msgContext.getTimeout());
    }
    // Always set the 30 second timeout on establishing the connection
    rcb.setConnectionRequestTimeout(10).setConnectTimeout(ComponentsHTTPSender.connectionTimeout);
    final Message msg = msgContext.getRequestMessage();
    if (msg != null) {
        method.setHeader(HTTPConstants.HEADER_CONTENT_TYPE, msg.getContentType(msgContext.getSOAPConstants()));
    }
    if (msgContext.useSOAPAction()) {
        // define SOAPAction header
        final String action = msgContext.getSOAPActionURI();
        if (action != null && !"".equals(action))
            method.setHeader(HTTPConstants.HEADER_SOAP_ACTION, "\"" + action + "\"");
    }
    String userID = msgContext.getUsername();
    String passwd = msgContext.getPassword();
    // the one in the URL.
    if ((userID == null) && (tmpURL.getUserInfo() != null)) {
        final String info = tmpURL.getUserInfo();
        final int sep = info.indexOf(':');
        if ((sep >= 0) && (sep + 1 < info.length())) {
            userID = info.substring(0, sep);
            passwd = info.substring(sep + 1);
        } else {
            userID = info;
        }
    }
    if (userID != null) {
        Credentials proxyCred = new UsernamePasswordCredentials(userID, passwd);
        // if the username is in the form "user\domain"
        // then use NTCredentials instead.
        final int domainIndex = userID.indexOf("\\");
        if (domainIndex > 0) {
            final String domain = userID.substring(0, domainIndex);
            if (userID.length() > domainIndex + 1) {
                final String user = userID.substring(domainIndex + 1);
                proxyCred = new NTCredentials(user, passwd, NetworkUtils.getLocalHostname(), domain);
            }
        }
        final BasicCredentialsProvider bcp = new BasicCredentialsProvider();
        bcp.setCredentials(AuthScope.ANY, proxyCred);
        httpContext.setCredentialsProvider(bcp);
    }
    // add compression headers if needed
    if (msgContext.isPropertyTrue(HTTPConstants.MC_ACCEPT_GZIP)) {
        method.addHeader(HTTPConstants.HEADER_ACCEPT_ENCODING, HTTPConstants.COMPRESSION_GZIP);
    }
    if (msgContext.isPropertyTrue(HTTPConstants.MC_GZIP_REQUEST)) {
        method.addHeader(HTTPConstants.HEADER_CONTENT_ENCODING, HTTPConstants.COMPRESSION_GZIP);
    }
    // Transfer MIME headers of SOAPMessage to HTTP headers.
    final MimeHeaders mimeHeaders = msg != null ? msg.getMimeHeaders() : null;
    if (mimeHeaders != null) {
        for (@SuppressWarnings("unchecked") final Iterator<MimeHeader> i = mimeHeaders.getAllHeaders(); i.hasNext(); ) {
            final MimeHeader mimeHeader = i.next();
            // HEADER_CONTENT_TYPE and HEADER_SOAP_ACTION are already set.
            // Let's not duplicate them.
            final String headerName = mimeHeader.getName();
            if (headerName.equals(HTTPConstants.HEADER_CONTENT_TYPE) || headerName.equals(HTTPConstants.HEADER_SOAP_ACTION)) {
                continue;
            }
            method.addHeader(mimeHeader.getName(), mimeHeader.getValue());
        }
    }
    // process user defined headers for information.
    final MimeHeaders userHeaders = (MimeHeaders) msgContext.getProperty(HTTPConstants.REQUEST_HEADERS);
    if (userHeaders != null) {
        for (@SuppressWarnings("unchecked") final Iterator<MimeHeader> i = userHeaders.getAllHeaders(); i.hasNext(); ) {
            final MimeHeader mimeHeader = i.next();
            final String key = mimeHeader.getName();
            final String value = mimeHeader.getValue();
            if (HTTPConstants.HEADER_EXPECT.equalsIgnoreCase(key) && HTTPConstants.HEADER_EXPECT_100_Continue.equalsIgnoreCase(value)) {
                rcb.setExpectContinueEnabled(true);
            } else if (HTTPConstants.HEADER_TRANSFER_ENCODING_CHUNKED.equalsIgnoreCase(key)) {
                if (null != value) {
                    this.httpChunkStream = JavaUtils.isTrue(value);
                }
            } else {
                method.addHeader(key, value);
            }
        }
    }
}
Also used : MimeHeaders(javax.xml.soap.MimeHeaders) BasicCredentialsProvider(org.apache.http.impl.client.BasicCredentialsProvider) Message(org.apache.axis.Message) MimeHeader(javax.xml.soap.MimeHeader) NTCredentials(org.apache.http.auth.NTCredentials) Credentials(org.apache.http.auth.Credentials) UsernamePasswordCredentials(org.apache.http.auth.UsernamePasswordCredentials) UsernamePasswordCredentials(org.apache.http.auth.UsernamePasswordCredentials) NTCredentials(org.apache.http.auth.NTCredentials)

Aggregations

NTCredentials (org.apache.http.auth.NTCredentials)63 AuthScope (org.apache.http.auth.AuthScope)41 BasicCredentialsProvider (org.apache.http.impl.client.BasicCredentialsProvider)33 UsernamePasswordCredentials (org.apache.http.auth.UsernamePasswordCredentials)30 CredentialsProvider (org.apache.http.client.CredentialsProvider)27 Credentials (org.apache.http.auth.Credentials)23 HttpHost (org.apache.http.HttpHost)22 HttpClientBuilder (org.apache.http.impl.client.HttpClientBuilder)11 RequestConfig (org.apache.http.client.config.RequestConfig)9 ConnectionSocketFactory (org.apache.http.conn.socket.ConnectionSocketFactory)9 PlainConnectionSocketFactory (org.apache.http.conn.socket.PlainConnectionSocketFactory)9 PoolingHttpClientConnectionManager (org.apache.http.impl.conn.PoolingHttpClientConnectionManager)9 SSLConnectionSocketFactory (org.apache.http.conn.ssl.SSLConnectionSocketFactory)6 CloseableHttpClient (org.apache.http.impl.client.CloseableHttpClient)6 LaxRedirectStrategy (org.apache.http.impl.client.LaxRedirectStrategy)5 HttpRequestExecutor (org.apache.http.protocol.HttpRequestExecutor)5 AuthSchemeProvider (org.apache.http.auth.AuthSchemeProvider)4 AuthenticationException (org.apache.http.auth.AuthenticationException)4 InvalidCredentialsException (org.apache.http.auth.InvalidCredentialsException)4 BufferedHeader (org.apache.http.message.BufferedHeader)4