Search in sources :

Example 66 with BasicScheme

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

the class DataConfig method getAuthScheme.

private AuthScheme getAuthScheme(final Map<String, String> paramMap, final String webAuthName, final String scheme) {
    AuthScheme authScheme = null;
    if (Constants.BASIC.equals(scheme)) {
        authScheme = new BasicScheme();
    } else if (Constants.DIGEST.equals(scheme)) {
        authScheme = new DigestScheme();
    } else if (Constants.NTLM.equals(scheme)) {
        final Properties props = new Properties();
        paramMap.entrySet().stream().filter(e -> e.getKey().startsWith("jcifs.")).forEach(e -> {
            props.setProperty(e.getKey(), e.getValue());
        });
        authScheme = new NTLMScheme(new JcifsEngine(props));
    } else if (Constants.FORM.equals(scheme)) {
        final String prefix = CRAWLER_WEB_AUTH + "." + webAuthName + ".";
        final Map<String, String> parameterMap = paramMap.entrySet().stream().filter(e -> e.getKey().startsWith(prefix)).collect(Collectors.toMap(e -> e.getKey().substring(prefix.length()), Entry::getValue));
        authScheme = new FormScheme(parameterMap);
    }
    return authScheme;
}
Also used : DigestScheme(org.apache.http.impl.auth.DigestScheme) Arrays(java.util.Arrays) Constants(org.codelibs.fess.Constants) AuthenticationImpl(org.codelibs.fess.crawler.client.http.impl.AuthenticationImpl) HcHttpClient(org.codelibs.fess.crawler.client.http.HcHttpClient) HashMap(java.util.HashMap) FormScheme(org.codelibs.fess.crawler.client.http.form.FormScheme) FtpClient(org.codelibs.fess.crawler.client.ftp.FtpClient) Authentication(org.codelibs.fess.crawler.client.http.Authentication) JcifsEngine(org.codelibs.fess.crawler.client.http.ntlm.JcifsEngine) CrawlerSystemException(org.codelibs.fess.crawler.exception.CrawlerSystemException) Supplier(java.util.function.Supplier) ArrayList(java.util.ArrayList) NTCredentials(org.apache.http.auth.NTCredentials) Credentials(org.apache.http.auth.Credentials) Map(java.util.Map) AuthScheme(org.apache.http.auth.AuthScheme) ParameterUtil(org.codelibs.fess.util.ParameterUtil) BasicScheme(org.apache.http.impl.auth.BasicScheme) Properties(java.util.Properties) StringUtil(org.codelibs.core.lang.StringUtil) Collectors(java.util.stream.Collectors) UsernamePasswordCredentials(org.apache.http.auth.UsernamePasswordCredentials) SmbAuthentication(org.codelibs.fess.crawler.client.smb.SmbAuthentication) List(java.util.List) Logger(org.apache.logging.log4j.Logger) NTLMScheme(org.apache.http.impl.auth.NTLMScheme) AuthScope(org.apache.http.auth.AuthScope) FtpAuthentication(org.codelibs.fess.crawler.client.ftp.FtpAuthentication) Entry(java.util.Map.Entry) DigestScheme(org.apache.http.impl.auth.DigestScheme) Pattern(java.util.regex.Pattern) BsDataConfig(org.codelibs.fess.es.config.bsentity.BsDataConfig) SmbClient(org.codelibs.fess.crawler.client.smb.SmbClient) Collections(java.util.Collections) LogManager(org.apache.logging.log4j.LogManager) CrawlerClientFactory(org.codelibs.fess.crawler.client.CrawlerClientFactory) BasicScheme(org.apache.http.impl.auth.BasicScheme) Entry(java.util.Map.Entry) NTLMScheme(org.apache.http.impl.auth.NTLMScheme) JcifsEngine(org.codelibs.fess.crawler.client.http.ntlm.JcifsEngine) Properties(java.util.Properties) HashMap(java.util.HashMap) Map(java.util.Map) FormScheme(org.codelibs.fess.crawler.client.http.form.FormScheme) AuthScheme(org.apache.http.auth.AuthScheme)

Example 67 with BasicScheme

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

the class OTHttpClientBuilder method build.

public OTHttpClient build() {
    HttpClientContext httpContext = HttpClientContext.create();
    // Basic authentication
    if (StringUtils.isNotBlank(username) && StringUtils.isNotBlank(password)) {
        CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
        credentialsProvider.setCredentials(new AuthScope(host), new UsernamePasswordCredentials(username, password));
        AuthCache authCache = new BasicAuthCache();
        authCache.put(host, new BasicScheme());
        httpContext.setCredentialsProvider(credentialsProvider);
        httpContext.setAuthCache(authCache);
    }
    CookieStore cookieStore = new BasicCookieStore();
    httpContext.setCookieStore(cookieStore);
    // SSL setup
    SSLConnectionSocketFactory sslSocketFactory;
    if (disableSsl) {
        logger.warn("Disabling SSL checks!");
        SSLContext ctx;
        try {
            X509TrustManager x509TrustManager = new X509TrustManager() {

                @Override
                public void checkClientTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
                }

                @Override
                public void checkServerTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
                }

                @Override
                public X509Certificate[] getAcceptedIssuers() {
                    return null;
                }
            };
            ctx = SSLContext.getInstance("TLS");
            ctx.init(new KeyManager[0], new TrustManager[] { x509TrustManager }, new SecureRandom());
        } catch (NoSuchAlgorithmException | KeyManagementException e) {
            throw new OTHttpClientSSLSetupException(e);
        }
        sslSocketFactory = new SSLConnectionSocketFactory(ctx, SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
    } else {
        sslSocketFactory = SSLConnectionSocketFactory.getSocketFactory();
    }
    Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create().register("http", PlainConnectionSocketFactory.getSocketFactory()).register("https", sslSocketFactory).build();
    Supplier<CloseableHttpClient> httpClientSupplier = () -> {
        // Defaults
        HttpClientBuilder builder = HttpClientBuilder.create().setConnectionManager(new PoolingHttpClientConnectionManager(registry));
        // OK
        return builder.build();
    };
    return new OTHttpClientImpl(url, host, httpClientSupplier, httpContext, clientLogger);
}
Also used : NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) SSLConnectionSocketFactory(org.apache.http.conn.ssl.SSLConnectionSocketFactory) KeyManagementException(java.security.KeyManagementException) PlainConnectionSocketFactory(org.apache.http.conn.socket.PlainConnectionSocketFactory) SSLConnectionSocketFactory(org.apache.http.conn.ssl.SSLConnectionSocketFactory) ConnectionSocketFactory(org.apache.http.conn.socket.ConnectionSocketFactory) BasicScheme(org.apache.http.impl.auth.BasicScheme) AuthCache(org.apache.http.client.AuthCache) SecureRandom(java.security.SecureRandom) HttpClientContext(org.apache.http.client.protocol.HttpClientContext) CredentialsProvider(org.apache.http.client.CredentialsProvider) SSLContext(javax.net.ssl.SSLContext) X509Certificate(java.security.cert.X509Certificate) UsernamePasswordCredentials(org.apache.http.auth.UsernamePasswordCredentials) PoolingHttpClientConnectionManager(org.apache.http.impl.conn.PoolingHttpClientConnectionManager) CookieStore(org.apache.http.client.CookieStore) X509TrustManager(javax.net.ssl.X509TrustManager) AuthScope(org.apache.http.auth.AuthScope)

Example 68 with BasicScheme

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

the class PreemtiveAuthorizationHttpRequestInterceptor method process.

public void process(final HttpRequest request, final HttpContext context) throws HttpException, IOException {
    AuthState authState = (AuthState) context.getAttribute(ClientContext.TARGET_AUTH_STATE);
    CredentialsProvider credsProvider = (CredentialsProvider) context.getAttribute(ClientContext.CREDS_PROVIDER);
    HttpHost targetHost = (HttpHost) context.getAttribute(ExecutionContext.HTTP_TARGET_HOST);
    if (authState.getAuthScheme() == null) {
        AuthScope authScope = new AuthScope(targetHost.getHostName(), targetHost.getPort());
        Credentials creds = credsProvider.getCredentials(authScope);
        if (creds != null) {
            authState.setAuthScheme(new BasicScheme());
            authState.setCredentials(creds);
        }
    }
}
Also used : BasicScheme(org.apache.http.impl.auth.BasicScheme) AuthState(org.apache.http.auth.AuthState) HttpHost(org.apache.http.HttpHost) AuthScope(org.apache.http.auth.AuthScope) CredentialsProvider(org.apache.http.client.CredentialsProvider) Credentials(org.apache.http.auth.Credentials)

Example 69 with BasicScheme

use of org.apache.http.impl.auth.BasicScheme in project zm-mailbox by Zimbra.

the class WebDavClient method setCredential.

public void setCredential(String user, String pass, String targetUrl) {
    mUsername = user;
    mPassword = pass;
    Credentials cred = new UsernamePasswordCredentials(mUsername, mPassword);
    CredentialsProvider provider = new BasicCredentialsProvider();
    provider.setCredentials(AuthScope.ANY, cred);
    HttpHost targetHost = new HttpHost(targetUrl);
    AuthCache authCache = new BasicAuthCache();
    authCache.put(targetHost, new BasicScheme());
    // Add AuthCache to the execution context
    context = HttpClientContext.create();
    context.setCredentialsProvider(provider);
    context.setAuthCache(authCache);
}
Also used : BasicScheme(org.apache.http.impl.auth.BasicScheme) BasicCredentialsProvider(org.apache.http.impl.client.BasicCredentialsProvider) HttpHost(org.apache.http.HttpHost) AuthCache(org.apache.http.client.AuthCache) BasicAuthCache(org.apache.http.impl.client.BasicAuthCache) BasicCredentialsProvider(org.apache.http.impl.client.BasicCredentialsProvider) CredentialsProvider(org.apache.http.client.CredentialsProvider) BasicAuthCache(org.apache.http.impl.client.BasicAuthCache) Credentials(org.apache.http.auth.Credentials) UsernamePasswordCredentials(org.apache.http.auth.UsernamePasswordCredentials) UsernamePasswordCredentials(org.apache.http.auth.UsernamePasswordCredentials)

Example 70 with BasicScheme

use of org.apache.http.impl.auth.BasicScheme in project zm-mailbox by Zimbra.

the class FeedManager method retrieveRemoteData.

private static RemoteDataInfo retrieveRemoteData(String url, Folder.SyncData fsd) throws ServiceException, HttpException, IOException {
    assert !Strings.isNullOrEmpty(url);
    HttpClientBuilder clientBuilder = ZimbraHttpConnectionManager.getExternalHttpConnMgr().newHttpClient();
    HttpProxyUtil.configureProxy(clientBuilder);
    // cannot set connection timeout because it'll affect all HttpClients associated with the conn mgr.
    // see comments in ZimbraHttpConnectionManager
    // client.setConnectionTimeout(10000);
    SocketConfig config = SocketConfig.custom().setSoTimeout(60000).build();
    clientBuilder.setDefaultSocketConfig(config);
    ConnectionConfig connConfig = ConnectionConfig.custom().setCharset(Charset.forName(MimeConstants.P_CHARSET_UTF8)).build();
    clientBuilder.setDefaultConnectionConfig(connConfig);
    HttpGet get = null;
    BufferedInputStream content = null;
    long lastModified = 0;
    String expectedCharset = MimeConstants.P_CHARSET_UTF8;
    int redirects = 0;
    int statusCode = HttpServletResponse.SC_NOT_FOUND;
    try {
        do {
            String lcurl = url.toLowerCase();
            if (lcurl.startsWith("webcal:")) {
                url = "http:" + url.substring(7);
            } else if (lcurl.startsWith("feed:")) {
                url = "http:" + url.substring(5);
            } else if (!lcurl.startsWith("http:") && !lcurl.startsWith("https:")) {
                throw ServiceException.INVALID_REQUEST("url must begin with http: or https:", null);
            }
            // Add AuthCache to the execution context
            HttpClientContext context = HttpClientContext.create();
            URIBuilder httpurl;
            try {
                httpurl = new URIBuilder(url);
            } catch (URISyntaxException e1) {
                throw ServiceException.INVALID_REQUEST("invalid url for feed: " + url, e1);
            }
            // validate target address (also handles followed `location` header addresses)
            if (isBlockedFeedAddress(httpurl)) {
                ZimbraLog.misc.info("Feed ip address blocked: %s. See localconfig for comma-separated ip list configuration: " + "zimbra_feed_manager_blacklist, zimbra_feed_manager_whitelist", url);
                throw ServiceException.INVALID_REQUEST(String.format("Address for feed is blocked: %s. See mailbox logs for details.", url), null);
            }
            // username and password are encoded in the URL as http://user:pass@host/...
            if (url.indexOf('@') != -1) {
                if (httpurl.getUserInfo() != null) {
                    String user = httpurl.getUserInfo();
                    if (user.indexOf('%') != -1) {
                        try {
                            user = URLDecoder.decode(user, "UTF-8");
                        } catch (OutOfMemoryError e) {
                            Zimbra.halt("out of memory", e);
                        } catch (Throwable t) {
                        }
                    }
                    int index = user.indexOf(':');
                    String userName = user.substring(0, index);
                    String password = user.substring(index + 1);
                    CredentialsProvider provider = new BasicCredentialsProvider();
                    UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(userName, password);
                    provider.setCredentials(AuthScope.ANY, credentials);
                    clientBuilder.setDefaultCredentialsProvider(provider);
                    // 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(new HttpHost(httpurl.getHost()), basicAuth);
                    // Add AuthCache to the execution context
                    context.setCredentialsProvider(provider);
                    context.setAuthCache(authCache);
                }
            }
            try {
                get = new HttpGet(url);
            } catch (OutOfMemoryError e) {
                Zimbra.halt("out of memory", e);
                return null;
            } catch (Throwable t) {
                ZimbraLog.misc.warnQuietly(String.format("invalid url for feed: %s", url), t);
                throw ServiceException.INVALID_REQUEST("invalid url for feed: " + url, null);
            }
            DefaultRedirectStrategy redirectStrategy = new DefaultRedirectStrategy();
            clientBuilder.setRedirectStrategy(redirectStrategy);
            get.addHeader("User-Agent", HTTP_USER_AGENT);
            get.addHeader("Accept", HTTP_ACCEPT);
            if (fsd != null && fsd.getLastSyncDate() > 0) {
                String lastSyncAt = DateUtils.formatDate(new Date(fsd.getLastSyncDate()));
                get.addHeader("If-Modified-Since", lastSyncAt);
            }
            HttpClient client = clientBuilder.build();
            HttpResponse response = HttpClientUtil.executeMethod(client, get, context);
            Header locationHeader = response.getFirstHeader("location");
            if (locationHeader != null) {
                // update our target URL and loop again to do another HTTP GET
                url = locationHeader.getValue();
                get.releaseConnection();
            } else {
                statusCode = response.getStatusLine().getStatusCode();
                if (statusCode == HttpServletResponse.SC_OK) {
                    Header contentEncoding = response.getFirstHeader("Content-Encoding");
                    InputStream respInputStream = response.getEntity().getContent();
                    if (contentEncoding != null) {
                        if (contentEncoding.getValue().indexOf("gzip") != -1) {
                            respInputStream = new GZIPInputStream(respInputStream);
                        }
                    }
                    content = new BufferedInputStream(respInputStream);
                    org.apache.http.entity.ContentType contentType = org.apache.http.entity.ContentType.getOrDefault(response.getEntity());
                    if (contentType != null && contentType.getCharset() != null) {
                        expectedCharset = contentType.getCharset().name();
                    }
                    Header lastModHdr = response.getFirstHeader("Last-Modified");
                    if (lastModHdr == null) {
                        lastModHdr = response.getFirstHeader("Date");
                    }
                    if (lastModHdr != null) {
                        Date d = DateUtils.parseDate(lastModHdr.getValue());
                        lastModified = d.getTime();
                    } else {
                        lastModified = System.currentTimeMillis();
                    }
                } else if (statusCode == HttpServletResponse.SC_NOT_MODIFIED) {
                    ZimbraLog.misc.debug("Remote data at " + url + " not modified since last sync");
                    return new RemoteDataInfo(statusCode, redirects, null, expectedCharset, lastModified);
                } else {
                    throw ServiceException.RESOURCE_UNREACHABLE(response.getStatusLine().toString(), null);
                }
                break;
            }
        } while (++redirects <= MAX_REDIRECTS);
    } catch (ServiceException ex) {
        if (get != null) {
            get.releaseConnection();
        }
        throw ex;
    } catch (HttpException ex) {
        if (get != null) {
            get.releaseConnection();
        }
        throw ex;
    } catch (IOException ex) {
        if (get != null) {
            get.releaseConnection();
        }
        throw ex;
    }
    RemoteDataInfo rdi = new RemoteDataInfo(statusCode, redirects, content, expectedCharset, lastModified);
    rdi.setGetMethod(get);
    return rdi;
}
Also used : BasicCredentialsProvider(org.apache.http.impl.client.BasicCredentialsProvider) HttpGet(org.apache.http.client.methods.HttpGet) HttpClientBuilder(org.apache.http.impl.client.HttpClientBuilder) URISyntaxException(java.net.URISyntaxException) BasicAuthCache(org.apache.http.impl.client.BasicAuthCache) GZIPInputStream(java.util.zip.GZIPInputStream) BufferedInputStream(java.io.BufferedInputStream) HttpHost(org.apache.http.HttpHost) DefaultRedirectStrategy(org.apache.http.impl.client.DefaultRedirectStrategy) HttpException(org.apache.http.HttpException) ConnectionConfig(org.apache.http.config.ConnectionConfig) BasicScheme(org.apache.http.impl.auth.BasicScheme) SocketConfig(org.apache.http.config.SocketConfig) GZIPInputStream(java.util.zip.GZIPInputStream) BufferedInputStream(java.io.BufferedInputStream) InputStream(java.io.InputStream) 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) BasicCredentialsProvider(org.apache.http.impl.client.BasicCredentialsProvider) CredentialsProvider(org.apache.http.client.CredentialsProvider) IOException(java.io.IOException) Date(java.util.Date) URIBuilder(org.apache.http.client.utils.URIBuilder) UsernamePasswordCredentials(org.apache.http.auth.UsernamePasswordCredentials) Header(org.apache.http.Header) ServiceException(com.zimbra.common.service.ServiceException) HttpClient(org.apache.http.client.HttpClient)

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