Search in sources :

Example 1 with UsernamePasswordCredentials

use of org.apache.hc.client5.http.auth.UsernamePasswordCredentials in project ecf by eclipse.

the class HttpClientProxyCredentialProvider method getCredentials.

@Override
public Credentials getCredentials(AuthScope authscope, HttpContext httpContext) {
    // $NON-NLS-1$
    Trace.entering(Activator.PLUGIN_ID, DebugOptions.METHODS_ENTERING, HttpClientProxyCredentialProvider.class, "getCredentials " + authscope);
    // First check to see whether given authscope matches any authscope
    // already cached.
    Credentials result = super.getCredentials(authscope, httpContext);
    // If we have a match, return credentials
    if (result != null) {
        if ("ntlm".equalsIgnoreCase(authscope.getSchemeName())) {
            // $NON-NLS-1$
            // We might have gotten these from a password prompt, making them
            // UsernamePasswordCredentials...
            Credentials fixed = fixNTCredentials(result);
            if (fixed != result) {
                result = fixed;
                setCredentials(authscope, fixed);
            }
        }
        return result;
    }
    // If we don't have a match, first get ECF proxy, if any
    Proxy proxy = getECFProxy();
    if (proxy == null)
        return null;
    // Make sure that authscope and proxy host and port match
    if (!matchAuthScopeAndProxy(authscope, proxy))
        return null;
    // Then match scheme, and get credentials from proxy (if it's scheme we know about)
    Credentials credentials = null;
    if ("ntlm".equalsIgnoreCase(authscope.getSchemeName())) {
        // $NON-NLS-1$
        credentials = getNTLMCredentials(proxy);
    } else if (// $NON-NLS-1$
    "basic".equalsIgnoreCase(authscope.getSchemeName()) || "digest".equalsIgnoreCase(authscope.getSchemeName())) {
        // $NON-NLS-1$
        final String proxyUsername = proxy.getUsername();
        final String proxyPassword = proxy.getPassword();
        // If credentials present for proxy then we're done
        if (proxyUsername != null) {
            credentials = new UsernamePasswordCredentials(proxyUsername, proxyPassword.toCharArray());
        }
    } else if ("negotiate".equalsIgnoreCase(authscope.getSchemeName())) {
        // $NON-NLS-1$
        // $NON-NLS-1$
        Trace.trace(Activator.PLUGIN_ID, "SPNEGO is not supported, if you can contribute support, please do so.");
    } else {
        // $NON-NLS-1$
        Trace.trace(Activator.PLUGIN_ID, "Unrecognized authentication scheme.");
    }
    // Put found credentials in cache for next time
    if (credentials != null)
        setCredentials(authscope, credentials);
    return credentials;
}
Also used : Proxy(org.eclipse.ecf.core.util.Proxy) Credentials(org.apache.hc.client5.http.auth.Credentials) UsernamePasswordCredentials(org.apache.hc.client5.http.auth.UsernamePasswordCredentials) NTCredentials(org.apache.hc.client5.http.auth.NTCredentials) UsernamePasswordCredentials(org.apache.hc.client5.http.auth.UsernamePasswordCredentials)

Example 2 with UsernamePasswordCredentials

use of org.apache.hc.client5.http.auth.UsernamePasswordCredentials in project ecf by eclipse.

the class HttpClientFileSystemBrowser method getFileRequestCredentials.

/**
 * Retrieves the credentials for requesting the file.
 * @return the {@link Credentials} necessary to retrieve the file
 * @throws UnsupportedCallbackException if the callback fails
 * @throws IOException if IO fails
 * @since 5.0
 */
protected Credentials getFileRequestCredentials() throws UnsupportedCallbackException, IOException {
    if (connectContext == null)
        return null;
    final CallbackHandler callbackHandler = connectContext.getCallbackHandler();
    if (callbackHandler == null)
        return null;
    final NameCallback usernameCallback = new NameCallback(USERNAME_PREFIX);
    final ObjectCallback passwordCallback = new ObjectCallback();
    callbackHandler.handle(new Callback[] { usernameCallback, passwordCallback });
    username = usernameCallback.getName();
    password = (String) passwordCallback.getObject();
    return new UsernamePasswordCredentials(username, password == null ? null : password.toCharArray());
}
Also used : CallbackHandler(org.eclipse.ecf.core.security.CallbackHandler) NameCallback(org.eclipse.ecf.core.security.NameCallback) ObjectCallback(org.eclipse.ecf.core.security.ObjectCallback) UsernamePasswordCredentials(org.apache.hc.client5.http.auth.UsernamePasswordCredentials)

Example 3 with UsernamePasswordCredentials

use of org.apache.hc.client5.http.auth.UsernamePasswordCredentials in project geo-platform by geosdi.

the class GeoSDIHttpClient5 method post.

/**
 * Executes an HTTP POST request against the provided URL, sending the contents of {@code
 * postContent} as the POST method body and setting the Content-Type request header to {@code
 * postContentType} if given, and returns the server response.
 *
 * <p>If an HTTP authentication {@link #getUser() user} and {@link #getPassword() password} is
 * set, the appropriate authentication HTTP header will be sent with the request.
 *
 * <p>If a {@link #getConnectTimeout() connection timeout} is set, the http connection will be
 * set to respect that timeout.
 *
 * <p>If a {@link #getReadTimeout() read timeout} is set, the http connection will be set to
 * respect it.
 *
 * @param url the URL against which to execute the POST request
 * @param postContent an input stream with the contents of the POST body
 * @param postContentType the MIME type of the contents sent as the request POST body, can be
 * {@code null}
 * @return the {@link HTTPResponse} encapsulating the response to the HTTP POST request
 */
@Override
public HTTPResponse post(URL url, InputStream postContent, String postContentType) throws IOException {
    HttpPost httpPost = new HttpPost(url.toExternalForm());
    logger.info("Inject OpenAM Cookie");
    if ((this.headers != null) && !(this.headers.isEmpty())) {
        List<String> values = this.headers.stream().map(value -> String.join("=", value.getHeaderKey(), value.getHeaderValue())).collect(toList());
        httpPost.setHeader("Cookie", String.join(";", values));
    }
    HttpEntity requestEntity = new InputStreamEntity(postContent, ContentType.create(postContentType));
    httpPost.setEntity(requestEntity);
    CloseableHttpResponse response = null;
    if (((this.user != null) && !(this.user.trim().isEmpty())) && ((this.password != null) && !(this.password.trim().isEmpty()))) {
        try {
            URI uri = url.toURI();
            HttpClientContext localContext = create();
            HttpHost targetHost = new HttpHost(uri.getScheme(), uri.getHost(), this.retrieveNoSetPort(uri));
            BasicScheme basicAuth = new BasicScheme();
            basicAuth.initPreemptive(new UsernamePasswordCredentials(this.user, this.password.toCharArray()));
            localContext.resetAuthExchange(targetHost, basicAuth);
            response = this.httpClient.execute(targetHost, httpPost, localContext);
        } catch (URISyntaxException ex) {
            throw new IOException("URISyntaxException error : " + ex.getMessage() + " for URL " + url.toExternalForm());
        }
    } else {
        response = this.httpClient.execute(httpPost);
    }
    int responseCode = response.getCode();
    if (200 != responseCode) {
        response.close();
        throw new IOException("Server returned HTTP error code " + responseCode + " for URL " + url.toExternalForm());
    } else {
        return new GeoSDIHttpClient5.HttpMethodResponse(response);
    }
}
Also used : GZIPInputStream(java.util.zip.GZIPInputStream) URL(java.net.URL) URISyntaxException(java.net.URISyntaxException) LoggerFactory(org.slf4j.LoggerFactory) ConnectionSocketFactory(org.apache.hc.client5.http.socket.ConnectionSocketFactory) BasicCredentialsProvider(org.apache.hc.client5.http.impl.auth.BasicCredentialsProvider) URI(java.net.URI) TimeValue(org.apache.hc.core5.util.TimeValue) HttpRequestExecutor(org.apache.hc.core5.http.impl.io.HttpRequestExecutor) RegistryBuilder(org.apache.hc.core5.http.config.RegistryBuilder) HTTPClient(org.geotools.http.HTTPClient) List(java.util.List) HttpEntity(org.apache.hc.core5.http.HttpEntity) UnsupportedCharsetException(java.nio.charset.UnsupportedCharsetException) DefaultConnectionReuseStrategy(org.apache.hc.core5.http.impl.DefaultConnectionReuseStrategy) TRUE(java.lang.Boolean.TRUE) Timeout.of(org.apache.hc.core5.util.Timeout.of) HttpClientContext(org.apache.hc.client5.http.protocol.HttpClientContext) BasicScheme(org.apache.hc.client5.http.impl.auth.BasicScheme) MINUTES(java.util.concurrent.TimeUnit.MINUTES) HttpGet(org.apache.hc.client5.http.classic.methods.HttpGet) HttpClientConnectionManager(org.apache.hc.client5.http.io.HttpClientConnectionManager) InputStreamEntity(org.apache.hc.core5.http.io.entity.InputStreamEntity) Lists(com.google.common.collect.Lists) Charset(java.nio.charset.Charset) HTTPResponse(org.geotools.http.HTTPResponse) CloseableHttpResponse(org.apache.hc.client5.http.impl.classic.CloseableHttpResponse) RequestConfig(org.apache.hc.client5.http.config.RequestConfig) HttpClients(org.apache.hc.client5.http.impl.classic.HttpClients) Logger(org.slf4j.Logger) UsernamePasswordCredentials(org.apache.hc.client5.http.auth.UsernamePasswordCredentials) WMSHeaderParam(org.geosdi.geoplatform.services.request.WMSHeaderParam) UTF_8(java.nio.charset.StandardCharsets.UTF_8) Header(org.apache.hc.core5.http.Header) NoopHostnameVerifier(org.apache.hc.client5.http.ssl.NoopHostnameVerifier) IOException(java.io.IOException) PoolingHttpClientConnectionManager(org.apache.hc.client5.http.impl.io.PoolingHttpClientConnectionManager) HttpPost(org.apache.hc.client5.http.classic.methods.HttpPost) SSLConnectionSocketFactory(org.apache.hc.client5.http.ssl.SSLConnectionSocketFactory) TimeUnit(java.util.concurrent.TimeUnit) SSLContextBuilder(org.apache.hc.core5.ssl.SSLContextBuilder) Collectors.toList(java.util.stream.Collectors.toList) HttpHost(org.apache.hc.core5.http.HttpHost) ContentType(org.apache.hc.core5.http.ContentType) PlainConnectionSocketFactory(org.apache.hc.client5.http.socket.PlainConnectionSocketFactory) Long.valueOf(java.lang.Long.valueOf) HttpClientContext.create(org.apache.hc.client5.http.protocol.HttpClientContext.create) CloseableHttpClient(org.apache.hc.client5.http.impl.classic.CloseableHttpClient) SECONDS(java.util.concurrent.TimeUnit.SECONDS) InputStream(java.io.InputStream) HttpPost(org.apache.hc.client5.http.classic.methods.HttpPost) BasicScheme(org.apache.hc.client5.http.impl.auth.BasicScheme) HttpEntity(org.apache.hc.core5.http.HttpEntity) HttpClientContext(org.apache.hc.client5.http.protocol.HttpClientContext) URISyntaxException(java.net.URISyntaxException) IOException(java.io.IOException) URI(java.net.URI) InputStreamEntity(org.apache.hc.core5.http.io.entity.InputStreamEntity) UsernamePasswordCredentials(org.apache.hc.client5.http.auth.UsernamePasswordCredentials) HttpHost(org.apache.hc.core5.http.HttpHost) CloseableHttpResponse(org.apache.hc.client5.http.impl.classic.CloseableHttpResponse)

Example 4 with UsernamePasswordCredentials

use of org.apache.hc.client5.http.auth.UsernamePasswordCredentials in project wiremock by wiremock.

the class WireMockTestClient method httpClientWithPreemptiveAuth.

private static CloseableHttpClient httpClientWithPreemptiveAuth(HttpHost target, String username, String password) {
    BasicCredentialsProvider credsProvider = new BasicCredentialsProvider();
    credsProvider.setCredentials(new AuthScope(target), new UsernamePasswordCredentials(username, password.toCharArray()));
    return HttpClients.custom().setDefaultCredentialsProvider(credsProvider).build();
}
Also used : BasicCredentialsProvider(org.apache.hc.client5.http.impl.auth.BasicCredentialsProvider) AuthScope(org.apache.hc.client5.http.auth.AuthScope) UsernamePasswordCredentials(org.apache.hc.client5.http.auth.UsernamePasswordCredentials)

Example 5 with UsernamePasswordCredentials

use of org.apache.hc.client5.http.auth.UsernamePasswordCredentials in project jahia by Jahia.

the class HttpClientService method initHttpClient.

private CloseableHttpClient initHttpClient(HttpClientBuilder builder, String protocol) {
    String host = System.getProperty(protocol + ".proxyHost");
    int port = Integer.getInteger(protocol + ".proxyPort", -1);
    HttpHost proxy = new HttpHost(protocol, host, port);
    builder.setProxy(proxy);
    String key = host + ':' + port;
    BasicCredentialsProvider credsProvider = null;
    String user = System.getProperty(protocol + ".proxyUser");
    if (StringUtils.isNotEmpty(user)) {
        credsProvider = new BasicCredentialsProvider();
        credsProvider.setCredentials(new AuthScope(proxy), new UsernamePasswordCredentials(user, System.getProperty(protocol + ".proxyPassword").toCharArray()));
        builder.setDefaultCredentialsProvider(credsProvider);
    }
    if (logger.isInfoEnabled()) {
        logger.info("Initialized HttpClient for {} protocol using proxy {} {} credentials", protocol.toUpperCase(), key, credsProvider != null ? "with" : "without");
    }
    CloseableHttpClient client = builder.build();
    httpClients.put(key, client);
    return client;
}
Also used : CloseableHttpClient(org.apache.hc.client5.http.impl.classic.CloseableHttpClient) BasicCredentialsProvider(org.apache.hc.client5.http.impl.auth.BasicCredentialsProvider) HttpHost(org.apache.hc.core5.http.HttpHost) AuthScope(org.apache.hc.client5.http.auth.AuthScope) UsernamePasswordCredentials(org.apache.hc.client5.http.auth.UsernamePasswordCredentials)

Aggregations

UsernamePasswordCredentials (org.apache.hc.client5.http.auth.UsernamePasswordCredentials)23 HttpHost (org.apache.hc.core5.http.HttpHost)13 BasicCredentialsProvider (org.apache.hc.client5.http.impl.auth.BasicCredentialsProvider)12 AuthScope (org.apache.hc.client5.http.auth.AuthScope)11 CloseableHttpClient (org.apache.hc.client5.http.impl.classic.CloseableHttpClient)10 CloseableHttpResponse (org.apache.hc.client5.http.impl.classic.CloseableHttpResponse)9 HttpClientContext (org.apache.hc.client5.http.protocol.HttpClientContext)9 HttpGet (org.apache.hc.client5.http.classic.methods.HttpGet)8 BasicScheme (org.apache.hc.client5.http.impl.auth.BasicScheme)7 IOException (java.io.IOException)5 Credentials (org.apache.hc.client5.http.auth.Credentials)5 URI (java.net.URI)3 NTCredentials (org.apache.hc.client5.http.auth.NTCredentials)3 RequestConfig (org.apache.hc.client5.http.config.RequestConfig)3 FileNotFoundException (java.io.FileNotFoundException)2 URISyntaxException (java.net.URISyntaxException)2 URL (java.net.URL)2 UTF_8 (java.nio.charset.StandardCharsets.UTF_8)2 List (java.util.List)2 CredentialsStore (org.apache.hc.client5.http.auth.CredentialsStore)2