Search in sources :

Example 36 with Credentials

use of org.apache.http.auth.Credentials in project lucene-solr by apache.

the class PreemptiveAuth method process.

@Override
public void process(final HttpRequest request, final HttpContext context) throws HttpException, IOException {
    AuthState authState = (AuthState) context.getAttribute(ClientContext.TARGET_AUTH_STATE);
    // If no auth scheme available yet, try to initialize it preemptively
    if (authState.getAuthScheme() == null) {
        CredentialsProvider credsProvider = (CredentialsProvider) context.getAttribute(ClientContext.CREDS_PROVIDER);
        Credentials creds = credsProvider.getCredentials(AuthScope.ANY);
        authState.update(authScheme, creds);
    }
}
Also used : AuthState(org.apache.http.auth.AuthState) CredentialsProvider(org.apache.http.client.CredentialsProvider) Credentials(org.apache.http.auth.Credentials)

Example 37 with Credentials

use of org.apache.http.auth.Credentials in project sling by apache.

the class TopologyConnectorClient method ping.

/** ping the server and pass the announcements between the two **/
void ping(final boolean force) {
    if (autoStopped) {
        // then we suppress any further pings!
        logger.debug("ping: autoStopped=true, hence suppressing any further pings.");
        return;
    }
    if (force) {
        backoffPeriodEnd = -1;
    } else if (backoffPeriodEnd > 0) {
        if (System.currentTimeMillis() < backoffPeriodEnd) {
            logger.debug("ping: not issueing a heartbeat due to backoff instruction from peer.");
            return;
        } else {
            logger.debug("ping: backoff period ended, issuing another ping now.");
        }
    }
    final String uri = connectorUrl.toString() + "." + clusterViewService.getSlingId() + ".json";
    if (logger.isDebugEnabled()) {
        logger.debug("ping: connectorUrl=" + connectorUrl + ", complete uri=" + uri);
    }
    final HttpClientContext clientContext = HttpClientContext.create();
    final CloseableHttpClient httpClient = createHttpClient();
    final HttpPut putRequest = new HttpPut(uri);
    // setting the connection timeout (idle connection, configured in seconds)
    putRequest.setConfig(RequestConfig.custom().setConnectTimeout(1000 * config.getSocketConnectTimeout()).build());
    Announcement resultingAnnouncement = null;
    try {
        String userInfo = connectorUrl.getUserInfo();
        if (userInfo != null) {
            Credentials c = new UsernamePasswordCredentials(userInfo);
            clientContext.getCredentialsProvider().setCredentials(new AuthScope(putRequest.getURI().getHost(), putRequest.getURI().getPort()), c);
        }
        Announcement topologyAnnouncement = new Announcement(clusterViewService.getSlingId());
        topologyAnnouncement.setServerInfo(serverInfo);
        final ClusterView clusterView;
        try {
            clusterView = clusterViewService.getLocalClusterView();
        } catch (UndefinedClusterViewException e) {
            // SLING-5030 : then we cannot ping
            logger.warn("ping: no clusterView available at the moment, cannot ping others now: " + e);
            return;
        }
        topologyAnnouncement.setLocalCluster(clusterView);
        if (force) {
            logger.debug("ping: sending a resetBackoff");
            topologyAnnouncement.setResetBackoff(true);
        }
        announcementRegistry.addAllExcept(topologyAnnouncement, clusterView, new AnnouncementFilter() {

            public boolean accept(final String receivingSlingId, final Announcement announcement) {
                // filter out announcements that are of old cluster instances
                // which I dont really have in my cluster view at the moment
                final Iterator<InstanceDescription> it = clusterView.getInstances().iterator();
                while (it.hasNext()) {
                    final InstanceDescription instance = it.next();
                    if (instance.getSlingId().equals(receivingSlingId)) {
                        // all fine then
                        return true;
                    }
                }
                // then I should also not propagate that announcement anywhere
                return false;
            }
        });
        final String p = requestValidator.encodeMessage(topologyAnnouncement.asJSON());
        if (logger.isDebugEnabled()) {
            logger.debug("ping: topologyAnnouncement json is: " + p);
        }
        requestValidator.trustMessage(putRequest, p);
        if (config.isGzipConnectorRequestsEnabled()) {
            // tell the server that the content is gzipped:
            putRequest.addHeader("Content-Encoding", "gzip");
            // and gzip the body:
            final ByteArrayOutputStream baos = new ByteArrayOutputStream();
            final GZIPOutputStream gzipOut = new GZIPOutputStream(baos);
            gzipOut.write(p.getBytes("UTF-8"));
            gzipOut.close();
            final byte[] gzippedEncodedJson = baos.toByteArray();
            putRequest.setEntity(new ByteArrayEntity(gzippedEncodedJson, ContentType.APPLICATION_JSON));
            lastRequestEncoding = "gzip";
        } else {
            // otherwise plaintext:
            final StringEntity plaintext = new StringEntity(p, "UTF-8");
            plaintext.setContentType(ContentType.APPLICATION_JSON.getMimeType());
            putRequest.setEntity(plaintext);
            lastRequestEncoding = "plaintext";
        }
        // independent of request-gzipping, we do accept the response to be gzipped,
        // so indicate this to the server:
        putRequest.addHeader("Accept-Encoding", "gzip");
        final CloseableHttpResponse response = httpClient.execute(putRequest, clientContext);
        if (logger.isDebugEnabled()) {
            logger.debug("ping: done. code=" + response.getStatusLine().getStatusCode() + " - " + response.getStatusLine().getReasonPhrase());
        }
        lastStatusCode = response.getStatusLine().getStatusCode();
        lastResponseEncoding = null;
        if (response.getStatusLine().getStatusCode() == HttpServletResponse.SC_OK) {
            final Header contentEncoding = response.getFirstHeader("Content-Encoding");
            if (contentEncoding != null && contentEncoding.getValue() != null && contentEncoding.getValue().contains("gzip")) {
                lastResponseEncoding = "gzip";
            } else {
                lastResponseEncoding = "plaintext";
            }
            // limiting to 16MB, should be way enough
            final String responseBody = requestValidator.decodeMessage(putRequest.getURI().getPath(), response);
            if (logger.isDebugEnabled()) {
                logger.debug("ping: response body=" + responseBody);
            }
            if (responseBody != null && responseBody.length() > 0) {
                Announcement inheritedAnnouncement = Announcement.fromJSON(responseBody);
                final long backoffInterval = inheritedAnnouncement.getBackoffInterval();
                if (backoffInterval > 0) {
                    // then reset the backoffPeriodEnd:
                    /* minus 1 sec to avoid slipping the interval by a few millis */
                    this.backoffPeriodEnd = System.currentTimeMillis() + (1000 * backoffInterval) - 1000;
                    logger.debug("ping: servlet instructed to backoff: backoffInterval=" + backoffInterval + ", resulting in period end of " + new Date(backoffPeriodEnd));
                } else {
                    logger.debug("ping: servlet did not instruct any backoff-ing at this stage");
                    this.backoffPeriodEnd = -1;
                }
                if (inheritedAnnouncement.isLoop()) {
                    if (logger.isDebugEnabled()) {
                        logger.debug("ping: connector response indicated a loop detected. not registering this announcement from " + inheritedAnnouncement.getOwnerId());
                    }
                    if (inheritedAnnouncement.getOwnerId().equals(clusterViewService.getSlingId())) {
                        if (config.isAutoStopLocalLoopEnabled()) {
                            // results in connected -> false and representsloop -> true
                            inheritedAnnouncement = null;
                            // results in isAutoStopped -> true
                            autoStopped = true;
                        }
                    }
                } else {
                    inheritedAnnouncement.setInherited(true);
                    if (announcementRegistry.registerAnnouncement(inheritedAnnouncement) == -1) {
                        if (logger.isDebugEnabled()) {
                            logger.debug("ping: connector response is from an instance which I already see in my topology" + inheritedAnnouncement);
                        }
                        statusDetails = "receiving side is seeing me via another path (connector or cluster) already (loop)";
                        return;
                    }
                }
                resultingAnnouncement = inheritedAnnouncement;
                statusDetails = null;
            } else {
                statusDetails = "no response body received";
            }
        } else {
            statusDetails = "got HTTP Status-Code: " + lastStatusCode;
        }
        // SLING-2882 : reset suppressPingWarnings_ flag in success case
        suppressPingWarnings_ = false;
    } catch (IOException e) {
        // SLING-2882 : set/check the suppressPingWarnings_ flag
        if (suppressPingWarnings_) {
            if (logger.isDebugEnabled()) {
                logger.debug("ping: got IOException: " + e + ", uri=" + uri);
            }
        } else {
            suppressPingWarnings_ = true;
            logger.warn("ping: got IOException [suppressing further warns]: " + e + ", uri=" + uri);
        }
        statusDetails = e.toString();
    } catch (JsonException e) {
        logger.warn("ping: got JSONException: " + e);
        statusDetails = e.toString();
    } catch (RuntimeException re) {
        logger.warn("ping: got RuntimeException: " + re, re);
        statusDetails = re.toString();
    } finally {
        putRequest.releaseConnection();
        lastInheritedAnnouncement = resultingAnnouncement;
        lastPingedAt = System.currentTimeMillis();
        try {
            httpClient.close();
        } catch (IOException e) {
            logger.error("disconnect: could not close httpClient: " + e, e);
        }
    }
}
Also used : ClusterView(org.apache.sling.discovery.ClusterView) JsonException(javax.json.JsonException) Announcement(org.apache.sling.discovery.base.connectors.announcement.Announcement) AnnouncementFilter(org.apache.sling.discovery.base.connectors.announcement.AnnouncementFilter) HttpPut(org.apache.http.client.methods.HttpPut) StringEntity(org.apache.http.entity.StringEntity) ByteArrayEntity(org.apache.http.entity.ByteArrayEntity) GZIPOutputStream(java.util.zip.GZIPOutputStream) Iterator(java.util.Iterator) CloseableHttpResponse(org.apache.http.client.methods.CloseableHttpResponse) CloseableHttpClient(org.apache.http.impl.client.CloseableHttpClient) HttpClientContext(org.apache.http.client.protocol.HttpClientContext) ByteArrayOutputStream(java.io.ByteArrayOutputStream) IOException(java.io.IOException) Date(java.util.Date) UsernamePasswordCredentials(org.apache.http.auth.UsernamePasswordCredentials) Header(org.apache.http.Header) AuthScope(org.apache.http.auth.AuthScope) UndefinedClusterViewException(org.apache.sling.discovery.base.commons.UndefinedClusterViewException) InstanceDescription(org.apache.sling.discovery.InstanceDescription) Credentials(org.apache.http.auth.Credentials) UsernamePasswordCredentials(org.apache.http.auth.UsernamePasswordCredentials)

Example 38 with Credentials

use of org.apache.http.auth.Credentials in project sling by apache.

the class TopologyConnectorClient method disconnect.

/** Disconnect this connector **/
public void disconnect() {
    final String uri = connectorUrl.toString() + "." + clusterViewService.getSlingId() + ".json";
    if (logger.isDebugEnabled()) {
        logger.debug("disconnect: connectorUrl=" + connectorUrl + ", complete uri=" + uri);
    }
    if (lastInheritedAnnouncement != null) {
        announcementRegistry.unregisterAnnouncement(lastInheritedAnnouncement.getOwnerId());
    }
    final HttpClientContext clientContext = HttpClientContext.create();
    final CloseableHttpClient httpClient = createHttpClient();
    final HttpDelete deleteRequest = new HttpDelete(uri);
    // setting the connection timeout (idle connection, configured in seconds)
    deleteRequest.setConfig(RequestConfig.custom().setConnectTimeout(1000 * config.getSocketConnectTimeout()).build());
    try {
        String userInfo = connectorUrl.getUserInfo();
        if (userInfo != null) {
            Credentials c = new UsernamePasswordCredentials(userInfo);
            clientContext.getCredentialsProvider().setCredentials(new AuthScope(deleteRequest.getURI().getHost(), deleteRequest.getURI().getPort()), c);
        }
        requestValidator.trustMessage(deleteRequest, null);
        final CloseableHttpResponse response = httpClient.execute(deleteRequest, clientContext);
        if (logger.isDebugEnabled()) {
            logger.debug("disconnect: done. code=" + response.getStatusLine().getStatusCode() + " - " + response.getStatusLine().getReasonPhrase());
        }
    // ignoring the actual statuscode though as there's little we can
    // do about it after this point
    } catch (IOException e) {
        logger.warn("disconnect: got IOException: " + e);
    } catch (RuntimeException re) {
        logger.error("disconnect: got RuntimeException: " + re, re);
    } finally {
        deleteRequest.releaseConnection();
        try {
            httpClient.close();
        } catch (IOException e) {
            logger.error("disconnect: could not close httpClient: " + e, e);
        }
    }
}
Also used : CloseableHttpClient(org.apache.http.impl.client.CloseableHttpClient) HttpDelete(org.apache.http.client.methods.HttpDelete) AuthScope(org.apache.http.auth.AuthScope) CloseableHttpResponse(org.apache.http.client.methods.CloseableHttpResponse) HttpClientContext(org.apache.http.client.protocol.HttpClientContext) IOException(java.io.IOException) Credentials(org.apache.http.auth.Credentials) UsernamePasswordCredentials(org.apache.http.auth.UsernamePasswordCredentials) UsernamePasswordCredentials(org.apache.http.auth.UsernamePasswordCredentials)

Example 39 with Credentials

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

the class DataConfig method initializeClientFactory.

@Override
public Map<String, Object> initializeClientFactory(final CrawlerClientFactory crawlerClientFactory) {
    final Map<String, String> paramMap = getHandlerParameterMap();
    final Map<String, Object> factoryParamMap = new HashMap<>();
    crawlerClientFactory.setInitParameterMap(factoryParamMap);
    // parameters
    for (final Map.Entry<String, String> entry : paramMap.entrySet()) {
        final String key = entry.getKey();
        if (key.startsWith(CRAWLER_PARAM_PREFIX)) {
            factoryParamMap.put(key.substring(CRAWLER_PARAM_PREFIX.length()), entry.getValue());
        }
    }
    // user agent
    final String userAgent = paramMap.get(CRAWLER_USERAGENT);
    if (StringUtil.isNotBlank(userAgent)) {
        factoryParamMap.put(HcHttpClient.USER_AGENT_PROPERTY, userAgent);
    }
    // web auth
    final String webAuthStr = paramMap.get(CRAWLER_WEB_AUTH);
    if (StringUtil.isNotBlank(webAuthStr)) {
        final String[] webAuthNames = webAuthStr.split(",");
        final List<Authentication> basicAuthList = new ArrayList<>();
        for (final String webAuthName : webAuthNames) {
            final String scheme = paramMap.get(CRAWLER_WEB_AUTH + "." + webAuthName + ".scheme");
            final String hostname = paramMap.get(CRAWLER_WEB_AUTH + "." + webAuthName + ".host");
            final String port = paramMap.get(CRAWLER_WEB_AUTH + "." + webAuthName + ".port");
            final String realm = paramMap.get(CRAWLER_WEB_AUTH + "." + webAuthName + ".realm");
            final String username = paramMap.get(CRAWLER_WEB_AUTH + "." + webAuthName + ".username");
            final String password = paramMap.get(CRAWLER_WEB_AUTH + "." + webAuthName + ".password");
            if (StringUtil.isEmpty(username)) {
                logger.warn("username is empty. webAuth:" + webAuthName);
                continue;
            }
            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)) {
                authScheme = new NTLMScheme(new JcifsEngine());
            }
            // TODO FORM
            AuthScope authScope;
            if (StringUtil.isBlank(hostname)) {
                authScope = AuthScope.ANY;
            } else {
                int p = AuthScope.ANY_PORT;
                if (StringUtil.isNotBlank(port)) {
                    try {
                        p = Integer.parseInt(port);
                    } catch (final NumberFormatException e) {
                        logger.warn("Failed to parse " + port, e);
                    }
                }
                String r = realm;
                if (StringUtil.isBlank(realm)) {
                    r = AuthScope.ANY_REALM;
                }
                String s = scheme;
                if (StringUtil.isBlank(scheme) || Constants.NTLM.equals(scheme)) {
                    s = AuthScope.ANY_SCHEME;
                }
                authScope = new AuthScope(hostname, p, r, s);
            }
            Credentials credentials;
            if (Constants.NTLM.equals(scheme)) {
                final String workstation = paramMap.get(CRAWLER_WEB_AUTH + "." + webAuthName + ".workstation");
                final String domain = paramMap.get(CRAWLER_WEB_AUTH + "." + webAuthName + ".domain");
                credentials = new NTCredentials(username, password == null ? StringUtil.EMPTY : password, workstation == null ? StringUtil.EMPTY : workstation, domain == null ? StringUtil.EMPTY : domain);
            } else {
                credentials = new UsernamePasswordCredentials(username, password == null ? StringUtil.EMPTY : password);
            }
            basicAuthList.add(new AuthenticationImpl(authScope, credentials, authScheme));
        }
        factoryParamMap.put(HcHttpClient.BASIC_AUTHENTICATIONS_PROPERTY, basicAuthList.toArray(new Authentication[basicAuthList.size()]));
    }
    // request header
    final List<org.codelibs.fess.crawler.client.http.RequestHeader> rhList = new ArrayList<>();
    int count = 1;
    String headerName = paramMap.get(CRAWLER_WEB_HEADER_PREFIX + count + ".name");
    while (StringUtil.isNotBlank(headerName)) {
        final String headerValue = paramMap.get(CRAWLER_WEB_HEADER_PREFIX + count + ".value");
        rhList.add(new org.codelibs.fess.crawler.client.http.RequestHeader(headerName, headerValue));
        count++;
        headerName = paramMap.get(CRAWLER_WEB_HEADER_PREFIX + count + ".name");
    }
    if (!rhList.isEmpty()) {
        factoryParamMap.put(HcHttpClient.REQUERT_HEADERS_PROPERTY, rhList.toArray(new org.codelibs.fess.crawler.client.http.RequestHeader[rhList.size()]));
    }
    // file auth
    final String fileAuthStr = paramMap.get(CRAWLER_FILE_AUTH);
    if (StringUtil.isNotBlank(fileAuthStr)) {
        final String[] fileAuthNames = fileAuthStr.split(",");
        final List<SmbAuthentication> smbAuthList = new ArrayList<>();
        final List<FtpAuthentication> ftpAuthList = new ArrayList<>();
        for (final String fileAuthName : fileAuthNames) {
            final String scheme = paramMap.get(CRAWLER_FILE_AUTH + "." + fileAuthName + ".scheme");
            if (Constants.SAMBA.equals(scheme)) {
                final String domain = paramMap.get(CRAWLER_FILE_AUTH + "." + fileAuthName + ".domain");
                final String hostname = paramMap.get(CRAWLER_FILE_AUTH + "." + fileAuthName + ".host");
                final String port = paramMap.get(CRAWLER_FILE_AUTH + "." + fileAuthName + ".port");
                final String username = paramMap.get(CRAWLER_FILE_AUTH + "." + fileAuthName + ".username");
                final String password = paramMap.get(CRAWLER_FILE_AUTH + "." + fileAuthName + ".password");
                if (StringUtil.isEmpty(username)) {
                    logger.warn("username is empty. fileAuth:" + fileAuthName);
                    continue;
                }
                final SmbAuthentication smbAuth = new SmbAuthentication();
                smbAuth.setDomain(domain == null ? StringUtil.EMPTY : domain);
                smbAuth.setServer(hostname);
                if (StringUtil.isNotBlank(port)) {
                    try {
                        smbAuth.setPort(Integer.parseInt(port));
                    } catch (final NumberFormatException e) {
                        logger.warn("Failed to parse " + port, e);
                    }
                }
                smbAuth.setUsername(username);
                smbAuth.setPassword(password == null ? StringUtil.EMPTY : password);
                smbAuthList.add(smbAuth);
            } else if (Constants.FTP.equals(scheme)) {
                final String hostname = paramMap.get(CRAWLER_FILE_AUTH + "." + fileAuthName + ".host");
                final String port = paramMap.get(CRAWLER_FILE_AUTH + "." + fileAuthName + ".port");
                final String username = paramMap.get(CRAWLER_FILE_AUTH + "." + fileAuthName + ".username");
                final String password = paramMap.get(CRAWLER_FILE_AUTH + "." + fileAuthName + ".password");
                if (StringUtil.isEmpty(username)) {
                    logger.warn("username is empty. fileAuth:" + fileAuthName);
                    continue;
                }
                final FtpAuthentication ftpAuth = new FtpAuthentication();
                ftpAuth.setServer(hostname);
                if (StringUtil.isNotBlank(port)) {
                    try {
                        ftpAuth.setPort(Integer.parseInt(port));
                    } catch (final NumberFormatException e) {
                        logger.warn("Failed to parse " + port, e);
                    }
                }
                ftpAuth.setUsername(username);
                ftpAuth.setPassword(password == null ? StringUtil.EMPTY : password);
                ftpAuthList.add(ftpAuth);
            }
        }
        if (!smbAuthList.isEmpty()) {
            factoryParamMap.put(SmbClient.SMB_AUTHENTICATIONS_PROPERTY, smbAuthList.toArray(new SmbAuthentication[smbAuthList.size()]));
        }
        if (!ftpAuthList.isEmpty()) {
            factoryParamMap.put(FtpClient.FTP_AUTHENTICATIONS_PROPERTY, ftpAuthList.toArray(new FtpAuthentication[ftpAuthList.size()]));
        }
    }
    return factoryParamMap;
}
Also used : HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) AuthScheme(org.apache.http.auth.AuthScheme) NTCredentials(org.apache.http.auth.NTCredentials) SmbAuthentication(org.codelibs.fess.crawler.client.smb.SmbAuthentication) DigestScheme(org.apache.http.impl.auth.DigestScheme) BasicScheme(org.apache.http.impl.auth.BasicScheme) FtpAuthentication(org.codelibs.fess.crawler.client.ftp.FtpAuthentication) JcifsEngine(org.codelibs.fess.crawler.client.http.ntlm.JcifsEngine) UsernamePasswordCredentials(org.apache.http.auth.UsernamePasswordCredentials) AuthenticationImpl(org.codelibs.fess.crawler.client.http.impl.AuthenticationImpl) Authentication(org.codelibs.fess.crawler.client.http.Authentication) SmbAuthentication(org.codelibs.fess.crawler.client.smb.SmbAuthentication) FtpAuthentication(org.codelibs.fess.crawler.client.ftp.FtpAuthentication) NTLMScheme(org.apache.http.impl.auth.NTLMScheme) AuthScope(org.apache.http.auth.AuthScope) HashMap(java.util.HashMap) Map(java.util.Map) NTCredentials(org.apache.http.auth.NTCredentials) Credentials(org.apache.http.auth.Credentials) UsernamePasswordCredentials(org.apache.http.auth.UsernamePasswordCredentials)

Aggregations

Credentials (org.apache.http.auth.Credentials)39 AuthScope (org.apache.http.auth.AuthScope)22 UsernamePasswordCredentials (org.apache.http.auth.UsernamePasswordCredentials)16 AuthScheme (org.apache.http.auth.AuthScheme)15 CredentialsProvider (org.apache.http.client.CredentialsProvider)13 AuthState (org.apache.http.auth.AuthState)11 AuthenticationException (org.apache.http.auth.AuthenticationException)9 HttpHost (org.apache.http.HttpHost)8 BasicCredentialsProvider (org.apache.http.impl.client.BasicCredentialsProvider)7 NTCredentials (org.apache.http.auth.NTCredentials)5 IOException (java.io.IOException)4 Header (org.apache.http.Header)4 HttpException (org.apache.http.HttpException)4 HttpRequest (org.apache.http.HttpRequest)4 HttpResponse (org.apache.http.HttpResponse)4 Scheme (org.apache.http.conn.scheme.Scheme)4 BasicScheme (org.apache.http.impl.auth.BasicScheme)4 HttpEntity (org.apache.http.HttpEntity)3 AbortableHttpRequest (org.apache.http.client.methods.AbortableHttpRequest)3 CloseableHttpResponse (org.apache.http.client.methods.CloseableHttpResponse)3