Search in sources :

Example 1 with NTCredentials

use of org.apache.http.auth.NTCredentials in project Xponents by OpenSextant.

the class SharepointClient method getClient.

/**
     * Sharepoint requires NTLM. This client requires a non-null user/passwd/domain.
     *
     */
@Override
public HttpClient getClient() {
    if (currentConn != null) {
        return currentConn;
    }
    HttpClientBuilder clientHelper = HttpClientBuilder.create();
    if (proxyHost != null) {
        clientHelper.setProxy(proxyHost);
    }
    RequestConfig globalConfig = RequestConfig.custom().setCookieSpec(CookieSpecs.BROWSER_COMPATIBILITY).build();
    CredentialsProvider creds = new BasicCredentialsProvider();
    creds.setCredentials(AuthScope.ANY, new NTCredentials(user, passwd, server, domain));
    clientHelper.setDefaultCredentialsProvider(creds);
    HttpClient httpClient = clientHelper.setDefaultRequestConfig(globalConfig).build();
    return httpClient;
}
Also used : RequestConfig(org.apache.http.client.config.RequestConfig) BasicCredentialsProvider(org.apache.http.impl.client.BasicCredentialsProvider) HttpClient(org.apache.http.client.HttpClient) HttpClientBuilder(org.apache.http.impl.client.HttpClientBuilder) BasicCredentialsProvider(org.apache.http.impl.client.BasicCredentialsProvider) CredentialsProvider(org.apache.http.client.CredentialsProvider) NTCredentials(org.apache.http.auth.NTCredentials)

Example 2 with NTCredentials

use of org.apache.http.auth.NTCredentials in project crawler4j by yasserg.

the class PageFetcher method doNtLogin.

/**
     * Do NT auth for Microsoft AD sites.
     */
private void doNtLogin(NtAuthInfo authInfo) {
    logger.info("NT authentication for: " + authInfo.getLoginTarget());
    HttpHost targetHost = new HttpHost(authInfo.getHost(), authInfo.getPort(), authInfo.getProtocol());
    CredentialsProvider credsProvider = new BasicCredentialsProvider();
    try {
        credsProvider.setCredentials(new AuthScope(targetHost.getHostName(), targetHost.getPort()), new NTCredentials(authInfo.getUsername(), authInfo.getPassword(), InetAddress.getLocalHost().getHostName(), authInfo.getDomain()));
    } catch (UnknownHostException e) {
        logger.error("Error creating NT credentials", e);
    }
    httpClient = HttpClients.custom().setDefaultCredentialsProvider(credsProvider).build();
}
Also used : BasicCredentialsProvider(org.apache.http.impl.client.BasicCredentialsProvider) UnknownHostException(java.net.UnknownHostException) HttpHost(org.apache.http.HttpHost) AuthScope(org.apache.http.auth.AuthScope) BasicCredentialsProvider(org.apache.http.impl.client.BasicCredentialsProvider) CredentialsProvider(org.apache.http.client.CredentialsProvider) NTCredentials(org.apache.http.auth.NTCredentials)

Example 3 with NTCredentials

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

the class HTTPHC4Impl method setupClient.

private CloseableHttpClient setupClient(URL url) {
    Map<HttpClientKey, CloseableHttpClient> mapHttpClientPerHttpClientKey = HTTPCLIENTS_CACHE_PER_THREAD_AND_HTTPCLIENTKEY.get();
    final String host = url.getHost();
    String proxyHost = getProxyHost();
    int proxyPort = getProxyPortInt();
    String proxyPass = getProxyPass();
    String proxyUser = getProxyUser();
    // static proxy is the globally define proxy eg command line or properties
    boolean useStaticProxy = isStaticProxy(host);
    // dynamic proxy is the proxy defined for this sampler
    boolean useDynamicProxy = isDynamicProxy(proxyHost, proxyPort);
    boolean useProxy = useStaticProxy || useDynamicProxy;
    // if both dynamic and static are used, the dynamic proxy has priority over static
    if (!useDynamicProxy) {
        proxyHost = PROXY_HOST;
        proxyPort = PROXY_PORT;
        proxyUser = PROXY_USER;
        proxyPass = PROXY_PASS;
    }
    // Lookup key - must agree with all the values used to create the HttpClient.
    HttpClientKey key = new HttpClientKey(url, useProxy, proxyHost, proxyPort, proxyUser, proxyPass);
    CloseableHttpClient httpClient = null;
    boolean concurrentDwn = this.testElement.isConcurrentDwn();
    if (concurrentDwn) {
        httpClient = (CloseableHttpClient) JMeterContextService.getContext().getSamplerContext().get(HTTPCLIENT_TOKEN);
    }
    if (httpClient == null) {
        httpClient = mapHttpClientPerHttpClientKey.get(key);
    }
    if (httpClient != null && resetSSLContext && HTTPConstants.PROTOCOL_HTTPS.equalsIgnoreCase(url.getProtocol())) {
        ((AbstractHttpClient) httpClient).clearRequestInterceptors();
        ((AbstractHttpClient) httpClient).clearResponseInterceptors();
        httpClient.getConnectionManager().closeIdleConnections(1L, TimeUnit.MICROSECONDS);
        httpClient = null;
        JsseSSLManager sslMgr = (JsseSSLManager) SSLManager.getInstance();
        sslMgr.resetContext();
        resetSSLContext = false;
    }
    if (httpClient == null) {
        // One-time init for this client
        HttpParams clientParams = new DefaultedHttpParams(new BasicHttpParams(), DEFAULT_HTTP_PARAMS);
        DnsResolver resolver = this.testElement.getDNSResolver();
        if (resolver == null) {
            resolver = SystemDefaultDnsResolver.INSTANCE;
        }
        MeasuringConnectionManager connManager = new MeasuringConnectionManager(createSchemeRegistry(), resolver, TIME_TO_LIVE, VALIDITY_AFTER_INACTIVITY_TIMEOUT);
        // to be realistic JMeter must set an higher value to DefaultMaxPerRoute
        if (concurrentDwn) {
            try {
                int maxConcurrentDownloads = Integer.parseInt(this.testElement.getConcurrentPool());
                connManager.setDefaultMaxPerRoute(Math.max(maxConcurrentDownloads, connManager.getDefaultMaxPerRoute()));
            } catch (NumberFormatException nfe) {
            // no need to log -> will be done by the sampler
            }
        }
        httpClient = new DefaultHttpClient(connManager, clientParams) {

            @Override
            protected HttpRequestRetryHandler createHttpRequestRetryHandler() {
                return new StandardHttpRequestRetryHandler(RETRY_COUNT, REQUEST_SENT_RETRY_ENABLED);
            }
        };
        if (IDLE_TIMEOUT > 0) {
            ((AbstractHttpClient) httpClient).setKeepAliveStrategy(IDLE_STRATEGY);
        }
        // see https://issues.apache.org/jira/browse/HTTPCORE-397
        ((AbstractHttpClient) httpClient).setReuseStrategy(DefaultClientConnectionReuseStrategy.INSTANCE);
        ((AbstractHttpClient) httpClient).addResponseInterceptor(RESPONSE_CONTENT_ENCODING);
        // HACK
        ((AbstractHttpClient) httpClient).addResponseInterceptor(METRICS_SAVER);
        ((AbstractHttpClient) httpClient).addRequestInterceptor(METRICS_RESETTER);
        // Override the default schemes as necessary
        SchemeRegistry schemeRegistry = httpClient.getConnectionManager().getSchemeRegistry();
        if (SLOW_HTTP != null) {
            schemeRegistry.register(SLOW_HTTP);
        }
        // Set up proxy details
        if (useProxy) {
            HttpHost proxy = new HttpHost(proxyHost, proxyPort);
            clientParams.setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
            if (proxyUser.length() > 0) {
                ((AbstractHttpClient) httpClient).getCredentialsProvider().setCredentials(new AuthScope(proxyHost, proxyPort), new NTCredentials(proxyUser, proxyPass, LOCALHOST, PROXY_DOMAIN));
            }
        }
        // Bug 52126 - we do our own cookie handling
        clientParams.setParameter(ClientPNames.COOKIE_POLICY, CookieSpecs.IGNORE_COOKIES);
        if (log.isDebugEnabled()) {
            log.debug("Created new HttpClient: @" + System.identityHashCode(httpClient) + " " + key.toString());
        }
        // save the agent for next time round
        mapHttpClientPerHttpClientKey.put(key, httpClient);
    } else {
        if (log.isDebugEnabled()) {
            log.debug("Reusing the HttpClient: @" + System.identityHashCode(httpClient) + " " + key.toString());
        }
    }
    if (concurrentDwn) {
        JMeterContextService.getContext().getSamplerContext().put(HTTPCLIENT_TOKEN, httpClient);
    }
    // TODO - should this be done when the client is created?
    // If so, then the details need to be added as part of HttpClientKey
    setConnectionAuthorization(httpClient, url, getAuthManager(), key);
    return httpClient;
}
Also used : CloseableHttpClient(org.apache.http.impl.client.CloseableHttpClient) SystemDefaultDnsResolver(org.apache.http.impl.conn.SystemDefaultDnsResolver) DnsResolver(org.apache.http.conn.DnsResolver) JsseSSLManager(org.apache.jmeter.util.JsseSSLManager) DefaultedHttpParams(org.apache.http.params.DefaultedHttpParams) DefaultHttpClient(org.apache.http.impl.client.DefaultHttpClient) StandardHttpRequestRetryHandler(org.apache.http.impl.client.StandardHttpRequestRetryHandler) NTCredentials(org.apache.http.auth.NTCredentials) AbstractHttpClient(org.apache.http.impl.client.AbstractHttpClient) DefaultedHttpParams(org.apache.http.params.DefaultedHttpParams) SyncBasicHttpParams(org.apache.http.params.SyncBasicHttpParams) HttpParams(org.apache.http.params.HttpParams) BasicHttpParams(org.apache.http.params.BasicHttpParams) HttpHost(org.apache.http.HttpHost) SchemeRegistry(org.apache.http.conn.scheme.SchemeRegistry) AuthScope(org.apache.http.auth.AuthScope) SyncBasicHttpParams(org.apache.http.params.SyncBasicHttpParams) BasicHttpParams(org.apache.http.params.BasicHttpParams) StandardHttpRequestRetryHandler(org.apache.http.impl.client.StandardHttpRequestRetryHandler) HttpRequestRetryHandler(org.apache.http.client.HttpRequestRetryHandler)

Example 4 with NTCredentials

use of org.apache.http.auth.NTCredentials in project XobotOS by xamarin.

the class NTLMScheme method authenticate.

public Header authenticate(final Credentials credentials, final HttpRequest request) throws AuthenticationException {
    NTCredentials ntcredentials = null;
    try {
        ntcredentials = (NTCredentials) credentials;
    } catch (ClassCastException e) {
        throw new InvalidCredentialsException("Credentials cannot be used for NTLM authentication: " + credentials.getClass().getName());
    }
    String response = null;
    if (this.state == State.CHALLENGE_RECEIVED || this.state == State.FAILED) {
        response = this.engine.generateType1Msg(ntcredentials.getDomain(), ntcredentials.getWorkstation());
        this.state = State.MSG_TYPE1_GENERATED;
    } else if (this.state == State.MSG_TYPE2_RECEVIED) {
        response = this.engine.generateType3Msg(ntcredentials.getUserName(), ntcredentials.getPassword(), ntcredentials.getDomain(), ntcredentials.getWorkstation(), this.challenge);
        this.state = State.MSG_TYPE3_GENERATED;
    } else {
        throw new AuthenticationException("Unexpected state: " + this.state);
    }
    CharArrayBuffer buffer = new CharArrayBuffer(32);
    if (isProxy()) {
        buffer.append(AUTH.PROXY_AUTH_RESP);
    } else {
        buffer.append(AUTH.WWW_AUTH_RESP);
    }
    buffer.append(": NTLM ");
    buffer.append(response);
    return new BufferedHeader(buffer);
}
Also used : InvalidCredentialsException(org.apache.http.auth.InvalidCredentialsException) AuthenticationException(org.apache.http.auth.AuthenticationException) BufferedHeader(org.apache.http.message.BufferedHeader) CharArrayBuffer(org.apache.http.util.CharArrayBuffer) NTCredentials(org.apache.http.auth.NTCredentials)

Example 5 with NTCredentials

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

the class HttpClientConfigurer method useCredentials.

private void useCredentials(CredentialsProvider credentialsProvider, String host, int port, Collection<? extends Authentication> authentications) {
    Credentials httpCredentials;
    for (Authentication authentication : authentications) {
        String scheme = getAuthScheme(authentication);
        PasswordCredentials credentials = getPasswordCredentials(authentication);
        if (authentication instanceof AllSchemesAuthentication) {
            NTLMCredentials ntlmCredentials = new NTLMCredentials(credentials);
            httpCredentials = new NTCredentials(ntlmCredentials.getUsername(), ntlmCredentials.getPassword(), ntlmCredentials.getWorkstation(), ntlmCredentials.getDomain());
            credentialsProvider.setCredentials(new AuthScope(host, port, AuthScope.ANY_REALM, AuthSchemes.NTLM), httpCredentials);
            LOGGER.debug("Using {} and {} for authenticating against '{}:{}' using {}", credentials, ntlmCredentials, host, port, AuthSchemes.NTLM);
        }
        httpCredentials = new UsernamePasswordCredentials(credentials.getUsername(), credentials.getPassword());
        credentialsProvider.setCredentials(new AuthScope(host, port, AuthScope.ANY_REALM, scheme), httpCredentials);
        LOGGER.debug("Using {} for authenticating against '{}:{}' using {}", credentials, host, port, scheme);
    }
}
Also used : PasswordCredentials(org.gradle.api.credentials.PasswordCredentials) UsernamePasswordCredentials(org.apache.http.auth.UsernamePasswordCredentials) NTLMCredentials(org.gradle.internal.resource.transport.http.ntlm.NTLMCredentials) Authentication(org.gradle.authentication.Authentication) DigestAuthentication(org.gradle.authentication.http.DigestAuthentication) AllSchemesAuthentication(org.gradle.internal.authentication.AllSchemesAuthentication) BasicAuthentication(org.gradle.authentication.http.BasicAuthentication) AuthScope(org.apache.http.auth.AuthScope) AllSchemesAuthentication(org.gradle.internal.authentication.AllSchemesAuthentication) PasswordCredentials(org.gradle.api.credentials.PasswordCredentials) NTCredentials(org.apache.http.auth.NTCredentials) NTLMCredentials(org.gradle.internal.resource.transport.http.ntlm.NTLMCredentials) Credentials(org.apache.http.auth.Credentials) UsernamePasswordCredentials(org.apache.http.auth.UsernamePasswordCredentials) NTCredentials(org.apache.http.auth.NTCredentials) UsernamePasswordCredentials(org.apache.http.auth.UsernamePasswordCredentials)

Aggregations

NTCredentials (org.apache.http.auth.NTCredentials)30 AuthScope (org.apache.http.auth.AuthScope)18 UsernamePasswordCredentials (org.apache.http.auth.UsernamePasswordCredentials)13 Credentials (org.apache.http.auth.Credentials)12 HttpHost (org.apache.http.HttpHost)10 BasicCredentialsProvider (org.apache.http.impl.client.BasicCredentialsProvider)10 CredentialsProvider (org.apache.http.client.CredentialsProvider)6 AuthenticationException (org.apache.http.auth.AuthenticationException)4 InvalidCredentialsException (org.apache.http.auth.InvalidCredentialsException)4 CloseableHttpClient (org.apache.http.impl.client.CloseableHttpClient)4 BufferedHeader (org.apache.http.message.BufferedHeader)4 CharArrayBuffer (org.apache.http.util.CharArrayBuffer)4 DefaultHttpClient (org.apache.http.impl.client.DefaultHttpClient)3 HttpParams (org.apache.http.params.HttpParams)3 UnknownHostException (java.net.UnknownHostException)2 RequestConfig (org.apache.http.client.config.RequestConfig)2 DnsResolver (org.apache.http.conn.DnsResolver)2 BasicScheme (org.apache.http.impl.auth.BasicScheme)2 PasswordCredentials (org.gradle.api.credentials.PasswordCredentials)2 Authentication (org.gradle.authentication.Authentication)2