Search in sources :

Example 36 with CredentialsProvider

use of org.apache.http.client.CredentialsProvider in project indy by Commonjava.

the class BasicAuthenticator method decoratePrototypeContext.

@Override
public HttpClientContext decoratePrototypeContext(AuthScope scope, SiteConfig location, PasswordType type, HttpClientContext ctx) {
    if (user != null) {
        final CredentialsProvider credProvider = new BasicCredentialsProvider();
        credProvider.setCredentials(scope, new UsernamePasswordCredentials(user, pass));
        ctx.setCredentialsProvider(credProvider);
    }
    return ctx;
}
Also used : BasicCredentialsProvider(org.apache.http.impl.client.BasicCredentialsProvider) BasicCredentialsProvider(org.apache.http.impl.client.BasicCredentialsProvider) CredentialsProvider(org.apache.http.client.CredentialsProvider) UsernamePasswordCredentials(org.apache.http.auth.UsernamePasswordCredentials)

Example 37 with CredentialsProvider

use of org.apache.http.client.CredentialsProvider in project stanbol by apache.

the class StanbolTestBase method waitForServerReady.

@Before
public void waitForServerReady() throws Exception {
    log.debug("> before {}#waitForServerReady()", getClass().getSimpleName());
    // initialize instance request builder and HTTP client
    builder = new RequestBuilder(serverBaseUrl);
    //TODO:user name and pwd
    String credentials = getCredentials();
    if (credentials != null && !credentials.isEmpty()) {
        CredentialsProvider credsProvider = new BasicCredentialsProvider();
        credsProvider.setCredentials(new AuthScope(HttpHost.create(serverBaseUrl)), new UsernamePasswordCredentials(credentials));
        httpClient = HttpClients.custom().setDefaultCredentialsProvider(credsProvider).build();
    } else {
        httpClient = HttpClients.createDefault();
    }
    executor = new RequestExecutor(httpClient);
    if (serverReady) {
        log.debug(" ... server already marked as ready!");
        return;
    }
    // Timeout for readiness test
    final String sec = System.getProperty(SERVER_READY_TIMEOUT_PROP);
    final int timeoutSec = sec == null ? 60 : Integer.valueOf(sec);
    log.info("Will wait up to " + timeoutSec + " seconds for server to become ready");
    final long endTime = System.currentTimeMillis() + timeoutSec * 1000L;
    // Get the list of paths to test and expected content regexps
    final List<String> testPaths = new ArrayList<String>();
    final TreeSet<Object> propertyNames = new TreeSet<Object>();
    propertyNames.addAll(System.getProperties().keySet());
    for (Object o : propertyNames) {
        final String key = (String) o;
        if (key.startsWith(SERVER_READY_PROP_PREFIX)) {
            testPaths.add(System.getProperty(key));
        }
    }
    // Consider the server ready if it responds to a GET on each of 
    // our configured request paths with a 200 result and content
    // that matches the regexp supplied with the path
    long sleepTime = 100;
    readyLoop: while (!serverReady && System.currentTimeMillis() < endTime) {
        // Wait a bit between checks, to let the server come up
        Thread.sleep(sleepTime);
        sleepTime = Math.min(5000L, sleepTime * 2);
        // A test path is in the form path:substring or just path, in which case
        // we don't check that the content contains the substring 
        log.debug(" - check serverReady Paths");
        for (String p : testPaths) {
            final String[] s = p.split(":");
            final String path = s[0];
            final String substring = (s.length > 0 ? s[1] : null);
            final String url = serverBaseUrl + path;
            log.debug("    > url: {}", url);
            log.debug("    > content: {}", substring);
            final HttpGet get = new HttpGet(url);
            //authenticate as admin with password admin
            get.setHeader("Authorization", "Basic YWRtaW46YWRtaW4=");
            for (int i = 2; i + 1 < s.length; i = i + 2) {
                log.debug("    > header: {}:{}", s[i], s[i + 1]);
                if (s[i] != null && !s[i].isEmpty() && s[i + 1] != null && !s[i + 1].isEmpty()) {
                    get.setHeader(s[i], s[i + 1]);
                }
            }
            CloseableHttpResponse response = null;
            HttpEntity entity = null;
            try {
                log.debug("    > execute: {}", get);
                response = httpClient.execute(get);
                log.debug("    > response: {}", response);
                entity = response.getEntity();
                final int status = response.getStatusLine().getStatusCode();
                if (status != 200) {
                    log.info("Got {} at {} - will retry", status, url);
                    continue readyLoop;
                } else {
                    log.debug("Got {} at {} - will retry", status, url);
                }
                if (substring != null) {
                    if (entity == null) {
                        log.info("No entity returned for {} - will retry", url);
                        continue readyLoop;
                    }
                    final String content = EntityUtils.toString(entity);
                    if (!content.contains(substring)) {
                        log.info("Returned content for {}  does not contain " + "{} - will retry", url, substring);
                        continue readyLoop;
                    }
                }
            } catch (HttpHostConnectException e) {
                log.info("Got HttpHostConnectException at " + url + " - will retry");
                continue readyLoop;
            } finally {
                EntityUtils.consumeQuietly(entity);
                if (response != null) {
                    response.close();
                }
            }
        }
        serverReady = true;
        log.info("Got expected content for all configured requests, server is ready");
    }
    if (!serverReady) {
        throw new Exception("Server not ready after " + timeoutSec + " seconds");
    }
}
Also used : BasicCredentialsProvider(org.apache.http.impl.client.BasicCredentialsProvider) RequestBuilder(org.apache.stanbol.commons.testing.http.RequestBuilder) HttpEntity(org.apache.http.HttpEntity) HttpGet(org.apache.http.client.methods.HttpGet) RequestExecutor(org.apache.stanbol.commons.testing.http.RequestExecutor) ArrayList(java.util.ArrayList) BasicCredentialsProvider(org.apache.http.impl.client.BasicCredentialsProvider) CredentialsProvider(org.apache.http.client.CredentialsProvider) HttpHostConnectException(org.apache.http.conn.HttpHostConnectException) MalformedURLException(java.net.MalformedURLException) UsernamePasswordCredentials(org.apache.http.auth.UsernamePasswordCredentials) TreeSet(java.util.TreeSet) AuthScope(org.apache.http.auth.AuthScope) CloseableHttpResponse(org.apache.http.client.methods.CloseableHttpResponse) HttpHostConnectException(org.apache.http.conn.HttpHostConnectException) Before(org.junit.Before)

Example 38 with CredentialsProvider

use of org.apache.http.client.CredentialsProvider in project sling by apache.

the class PreemptiveAuthInterceptor method process.

public void process(HttpRequest request, 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 not auth scheme has been initialized yet
    if (authState.getAuthScheme() == null) {
        AuthScope authScope = new AuthScope(targetHost.getHostName(), targetHost.getPort());
        // Obtain credentials matching the target host
        Credentials creds = credsProvider.getCredentials(authScope);
        // If found, generate BasicScheme preemptively
        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 39 with CredentialsProvider

use of org.apache.http.client.CredentialsProvider in project SmartApplianceEnabler by camueller.

the class HttpTransactionExecutor method sendHttpRequest.

/**
     * Send a HTTP request whose response has to be closed by the caller!
     * @param url
     * @return
     */
protected CloseableHttpResponse sendHttpRequest(String url, String data, ContentType contentType, String username, String password) {
    HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
    if (username != null && password != null) {
        CredentialsProvider provider = new BasicCredentialsProvider();
        UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(username, password);
        provider.setCredentials(AuthScope.ANY, credentials);
        httpClientBuilder.setDefaultCredentialsProvider(provider);
    }
    CloseableHttpClient client = httpClientBuilder.build();
    logger.debug("Sending HTTP request");
    logger.debug("url=" + url);
    logger.debug("data=" + data);
    logger.debug("contentType=" + contentType);
    logger.debug("username=" + username);
    logger.debug("password=" + password);
    try {
        HttpRequestBase request = null;
        if (data != null) {
            request = new HttpPost(url);
            ((HttpPost) request).setEntity(new StringEntity(data, contentType));
        } else {
            request = new HttpGet(url);
        }
        CloseableHttpResponse response = client.execute(request);
        int responseCode = response.getStatusLine().getStatusCode();
        logger.debug("Response code is " + responseCode);
        return response;
    } catch (IOException e) {
        logger.error("Error executing HTTP request.", e);
        return null;
    }
}
Also used : CloseableHttpClient(org.apache.http.impl.client.CloseableHttpClient) HttpPost(org.apache.http.client.methods.HttpPost) StringEntity(org.apache.http.entity.StringEntity) BasicCredentialsProvider(org.apache.http.impl.client.BasicCredentialsProvider) HttpRequestBase(org.apache.http.client.methods.HttpRequestBase) HttpGet(org.apache.http.client.methods.HttpGet) CloseableHttpResponse(org.apache.http.client.methods.CloseableHttpResponse) HttpClientBuilder(org.apache.http.impl.client.HttpClientBuilder) BasicCredentialsProvider(org.apache.http.impl.client.BasicCredentialsProvider) CredentialsProvider(org.apache.http.client.CredentialsProvider) IOException(java.io.IOException) UsernamePasswordCredentials(org.apache.http.auth.UsernamePasswordCredentials)

Example 40 with CredentialsProvider

use of org.apache.http.client.CredentialsProvider in project weixin-java-tools by chanjarster.

the class WxMpServiceImpl method setWxMpConfigStorage.

public void setWxMpConfigStorage(WxMpConfigStorage wxConfigProvider) {
    this.wxMpConfigStorage = wxConfigProvider;
    String http_proxy_host = wxMpConfigStorage.getHttp_proxy_host();
    int http_proxy_port = wxMpConfigStorage.getHttp_proxy_port();
    String http_proxy_username = wxMpConfigStorage.getHttp_proxy_username();
    String http_proxy_password = wxMpConfigStorage.getHttp_proxy_password();
    final HttpClientBuilder builder = HttpClients.custom();
    if (StringUtils.isNotBlank(http_proxy_host)) {
        // 使用代理服务器
        if (StringUtils.isNotBlank(http_proxy_username)) {
            // 需要用户认证的代理服务器
            CredentialsProvider credsProvider = new BasicCredentialsProvider();
            credsProvider.setCredentials(new AuthScope(http_proxy_host, http_proxy_port), new UsernamePasswordCredentials(http_proxy_username, http_proxy_password));
            builder.setDefaultCredentialsProvider(credsProvider);
        } else {
        // 无需用户认证的代理服务器
        }
        httpProxy = new HttpHost(http_proxy_host, http_proxy_port);
    }
    if (wxConfigProvider.getSSLContext() != null) {
        SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(wxConfigProvider.getSSLContext(), new String[] { "TLSv1" }, null, SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
        builder.setSSLSocketFactory(sslsf);
    }
    httpClient = builder.build();
}
Also used : BasicCredentialsProvider(org.apache.http.impl.client.BasicCredentialsProvider) HttpHost(org.apache.http.HttpHost) AuthScope(org.apache.http.auth.AuthScope) HttpClientBuilder(org.apache.http.impl.client.HttpClientBuilder) CredentialsProvider(org.apache.http.client.CredentialsProvider) BasicCredentialsProvider(org.apache.http.impl.client.BasicCredentialsProvider) SSLConnectionSocketFactory(org.apache.http.conn.ssl.SSLConnectionSocketFactory) UsernamePasswordCredentials(org.apache.http.auth.UsernamePasswordCredentials)

Aggregations

CredentialsProvider (org.apache.http.client.CredentialsProvider)79 BasicCredentialsProvider (org.apache.http.impl.client.BasicCredentialsProvider)52 UsernamePasswordCredentials (org.apache.http.auth.UsernamePasswordCredentials)50 AuthScope (org.apache.http.auth.AuthScope)43 HttpHost (org.apache.http.HttpHost)26 HttpGet (org.apache.http.client.methods.HttpGet)16 CloseableHttpClient (org.apache.http.impl.client.CloseableHttpClient)16 HttpResponse (org.apache.http.HttpResponse)15 Test (org.junit.Test)14 Credentials (org.apache.http.auth.Credentials)13 IOException (java.io.IOException)12 Header (org.apache.http.Header)11 HttpClientContext (org.apache.http.client.protocol.HttpClientContext)11 HttpRequest (org.apache.http.HttpRequest)10 BasicScheme (org.apache.http.impl.auth.BasicScheme)9 HttpClientBuilder (org.apache.http.impl.client.HttpClientBuilder)9 HttpEntity (org.apache.http.HttpEntity)8 AuthenticationException (org.apache.http.auth.AuthenticationException)8 AbortableHttpRequest (org.apache.http.client.methods.AbortableHttpRequest)8 CloseableHttpResponse (org.apache.http.client.methods.CloseableHttpResponse)8