Search in sources :

Example 26 with BasicCredentialsProvider

use of org.apache.http.impl.client.BasicCredentialsProvider in project wildfly by wildfly.

the class Utils method makeHttpCallWithFallback.

/**
     * Creates request against SPNEGO protected web-app with FORM fallback. It tries to login using SPNEGO first - if it fails,
     * FORM is used.
     *
     * @param contextUrl
     * @param page
     * @param user
     * @param pass
     * @param expectedStatusCode
     * @return
     * @throws IOException
     * @throws URISyntaxException
     * @throws PrivilegedActionException
     * @throws LoginException
     */
public static String makeHttpCallWithFallback(final String contextUrl, final String page, final String user, final String pass, final int expectedStatusCode) throws IOException, URISyntaxException, PrivilegedActionException, LoginException {
    final String strippedContextUrl = StringUtils.stripEnd(contextUrl, "/");
    final String url = strippedContextUrl + page;
    LOGGER.trace("Requesting URL: " + url);
    String unauthorizedPageBody = null;
    final Krb5LoginConfiguration krb5Configuration = new Krb5LoginConfiguration(getLoginConfiguration());
    Registry<AuthSchemeProvider> authSchemeRegistry = RegistryBuilder.<AuthSchemeProvider>create().register(AuthSchemes.SPNEGO, new JBossNegotiateSchemeFactory(true)).build();
    CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
    credentialsProvider.setCredentials(new AuthScope(null, -1, null), new NullHCCredentials());
    final CloseableHttpClient httpClient = HttpClientBuilder.create().setDefaultAuthSchemeRegistry(authSchemeRegistry).setDefaultCredentialsProvider(credentialsProvider).setRedirectStrategy(REDIRECT_STRATEGY).setConnectionManager(new BasicHttpClientConnectionManager()).build();
    try {
        final HttpGet httpGet = new HttpGet(url);
        final HttpResponse response = httpClient.execute(httpGet);
        int statusCode = response.getStatusLine().getStatusCode();
        if (HttpServletResponse.SC_UNAUTHORIZED != statusCode || StringUtils.isEmpty(user)) {
            assertEquals("Unexpected HTTP response status code.", expectedStatusCode, statusCode);
            return EntityUtils.toString(response.getEntity());
        }
        final Header[] authnHeaders = response.getHeaders("WWW-Authenticate");
        assertTrue("WWW-Authenticate header is present", authnHeaders != null && authnHeaders.length > 0);
        final Set<String> authnHeaderValues = new HashSet<String>();
        for (final Header header : authnHeaders) {
            authnHeaderValues.add(header.getValue());
        }
        assertTrue("WWW-Authenticate: Negotiate header is missing", authnHeaderValues.contains("Negotiate"));
        LOGGER.debug("HTTP response was SC_UNAUTHORIZED, let's authenticate the user " + user);
        unauthorizedPageBody = EntityUtils.toString(response.getEntity());
        // Use our custom configuration to avoid reliance on external config
        Configuration.setConfiguration(krb5Configuration);
        // 1. Authenticate to Kerberos.
        final LoginContext lc = loginWithKerberos(krb5Configuration, user, pass);
        // 2. Perform the work as authenticated Subject.
        final String responseBody = Subject.doAs(lc.getSubject(), new PrivilegedExceptionAction<String>() {

            public String run() throws Exception {
                final HttpResponse response = httpClient.execute(httpGet);
                int statusCode = response.getStatusLine().getStatusCode();
                assertEquals("Unexpected status code returned after the authentication.", expectedStatusCode, statusCode);
                return EntityUtils.toString(response.getEntity());
            }
        });
        lc.logout();
        return responseBody;
    } catch (LoginException e) {
        assertNotNull(unauthorizedPageBody);
        assertTrue(unauthorizedPageBody.contains("j_security_check"));
        HttpPost httpPost = new HttpPost(strippedContextUrl + "/j_security_check");
        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
        nameValuePairs.add(new BasicNameValuePair("j_username", user));
        nameValuePairs.add(new BasicNameValuePair("j_password", pass));
        httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
        final HttpResponse response = httpClient.execute(httpPost);
        int statusCode = response.getStatusLine().getStatusCode();
        assertEquals("Unexpected status code returned after the authentication.", expectedStatusCode, statusCode);
        return EntityUtils.toString(response.getEntity());
    } finally {
        // When HttpClient instance is no longer needed,
        // shut down the connection manager to ensure
        // immediate deallocation of all system resources
        httpClient.close();
        // reset login configuration
        krb5Configuration.resetConfiguration();
    }
}
Also used : HttpPost(org.apache.http.client.methods.HttpPost) BasicCredentialsProvider(org.apache.http.impl.client.BasicCredentialsProvider) HttpGet(org.apache.http.client.methods.HttpGet) LoginContext(javax.security.auth.login.LoginContext) BasicNameValuePair(org.apache.http.message.BasicNameValuePair) List(java.util.List) ArrayList(java.util.ArrayList) BasicHttpClientConnectionManager(org.apache.http.impl.conn.BasicHttpClientConnectionManager) HashSet(java.util.HashSet) JBossNegotiateSchemeFactory(org.jboss.as.test.integration.security.common.negotiation.JBossNegotiateSchemeFactory) CloseableHttpClient(org.apache.http.impl.client.CloseableHttpClient) NameValuePair(org.apache.http.NameValuePair) BasicNameValuePair(org.apache.http.message.BasicNameValuePair) HttpResponse(org.apache.http.HttpResponse) BasicCredentialsProvider(org.apache.http.impl.client.BasicCredentialsProvider) CredentialsProvider(org.apache.http.client.CredentialsProvider) UrlEncodedFormEntity(org.apache.http.client.entity.UrlEncodedFormEntity) LoginException(javax.security.auth.login.LoginException) ProtocolException(org.apache.http.ProtocolException) URISyntaxException(java.net.URISyntaxException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) PrivilegedActionException(java.security.PrivilegedActionException) MalformedURLException(java.net.MalformedURLException) IOException(java.io.IOException) UnknownHostException(java.net.UnknownHostException) Header(org.apache.http.Header) AuthScope(org.apache.http.auth.AuthScope) LoginException(javax.security.auth.login.LoginException) AuthSchemeProvider(org.apache.http.auth.AuthSchemeProvider)

Example 27 with BasicCredentialsProvider

use of org.apache.http.impl.client.BasicCredentialsProvider in project intellij-community by JetBrains.

the class GithubConnectionBuilder method setupCredentialsProvider.

@NotNull
private CredentialsProvider setupCredentialsProvider(@NotNull HttpClientBuilder builder) {
    CredentialsProvider provider = new BasicCredentialsProvider();
    // Basic authentication
    GithubAuthData.BasicAuth basicAuth = myAuth.getBasicAuth();
    if (basicAuth != null) {
        AuthScope authScope = getBasicAuthScope();
        provider.setCredentials(authScope, new UsernamePasswordCredentials(basicAuth.getLogin(), basicAuth.getPassword()));
        builder.addInterceptorFirst(new PreemptiveBasicAuthInterceptor(authScope));
    }
    builder.setDefaultCredentialsProvider(provider);
    if (myAuth.isUseProxy()) {
        IdeHttpClientHelpers.ApacheHttpClient4.setProxyCredentialsForUrlIfEnabled(provider, myApiURL);
    }
    return provider;
}
Also used : BasicCredentialsProvider(org.apache.http.impl.client.BasicCredentialsProvider) AuthScope(org.apache.http.auth.AuthScope) GithubAuthData(org.jetbrains.plugins.github.util.GithubAuthData) BasicCredentialsProvider(org.apache.http.impl.client.BasicCredentialsProvider) CredentialsProvider(org.apache.http.client.CredentialsProvider) UsernamePasswordCredentials(org.apache.http.auth.UsernamePasswordCredentials) NotNull(org.jetbrains.annotations.NotNull)

Example 28 with BasicCredentialsProvider

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

the class AbstractHttproxFunctionalTest method proxyContext.

protected HttpClientContext proxyContext(final String user, final String pass) {
    final CredentialsProvider creds = new BasicCredentialsProvider();
    creds.setCredentials(new AuthScope(HOST, proxyPort), new UsernamePasswordCredentials(user, pass));
    final HttpClientContext ctx = HttpClientContext.create();
    ctx.setCredentialsProvider(creds);
    return ctx;
}
Also used : BasicCredentialsProvider(org.apache.http.impl.client.BasicCredentialsProvider) AuthScope(org.apache.http.auth.AuthScope) HttpClientContext(org.apache.http.client.protocol.HttpClientContext) BasicCredentialsProvider(org.apache.http.impl.client.BasicCredentialsProvider) CredentialsProvider(org.apache.http.client.CredentialsProvider) UsernamePasswordCredentials(org.apache.http.auth.UsernamePasswordCredentials)

Example 29 with BasicCredentialsProvider

use of org.apache.http.impl.client.BasicCredentialsProvider 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 30 with BasicCredentialsProvider

use of org.apache.http.impl.client.BasicCredentialsProvider 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)

Aggregations

BasicCredentialsProvider (org.apache.http.impl.client.BasicCredentialsProvider)75 UsernamePasswordCredentials (org.apache.http.auth.UsernamePasswordCredentials)63 CredentialsProvider (org.apache.http.client.CredentialsProvider)48 AuthScope (org.apache.http.auth.AuthScope)41 HttpHost (org.apache.http.HttpHost)22 CloseableHttpClient (org.apache.http.impl.client.CloseableHttpClient)20 HttpResponse (org.apache.http.HttpResponse)16 HttpGet (org.apache.http.client.methods.HttpGet)16 HttpClient (org.apache.http.client.HttpClient)14 HttpClientContext (org.apache.http.client.protocol.HttpClientContext)14 IOException (java.io.IOException)13 HttpClientBuilder (org.apache.http.impl.client.HttpClientBuilder)10 AuthCache (org.apache.http.client.AuthCache)9 RequestConfig (org.apache.http.client.config.RequestConfig)9 BasicAuthCache (org.apache.http.impl.client.BasicAuthCache)9 CloseableHttpResponse (org.apache.http.client.methods.CloseableHttpResponse)8 BasicScheme (org.apache.http.impl.auth.BasicScheme)8 Test (org.junit.Test)8 HttpEntity (org.apache.http.HttpEntity)6 AuthSchemeProvider (org.apache.http.auth.AuthSchemeProvider)6