Example usage for org.apache.http.client.config AuthSchemes BASIC

List of usage examples for org.apache.http.client.config AuthSchemes BASIC

Introduction

In this page you can find the example usage for org.apache.http.client.config AuthSchemes BASIC.

Prototype

String BASIC

To view the source code for org.apache.http.client.config AuthSchemes BASIC.

Click Source Link

Document

Basic authentication scheme as defined in RFC2617 (considered inherently insecure, but most widely supported)

Usage

From source file:net.yacy.cora.protocol.http.HTTPClient.java

/**
 * Send data using HTTP POST method to the server named by vhost
 *
 * @param url address to request on the server
 * @param vhost name of the server at address which should respond. When null, localhost is assumed.
 * @param post data to send (name-value-pairs)
 * @param userName user name for HTTP authentication : only sent when requesting localhost
 * @param password encoded password for HTTP authentication : only sent when requesting localhost
 * @param usegzip if the body should be gzipped
 * @return response body//from  w  ww  .ja  va2s .  com
 * @throws IOException when an error occurred
 */
public byte[] POSTbytes(final MultiProtocolURL url, final String vhost, final Map<String, ContentBody> post,
        final String userName, final String password, final boolean usegzip, final boolean concurrent)
        throws IOException {
    final HttpPost httpPost = new HttpPost(url.toNormalform(true));
    final boolean localhost = Domains.isLocalhost(url.getHost());
    if (!localhost)
        setHost(url.getHost()); // overwrite resolved IP, needed for shared web hosting DO NOT REMOVE, see http://en.wikipedia.org/wiki/Shared_web_hosting_service
    if (vhost == null)
        setHost(Domains.LOCALHOST);

    final MultipartEntityBuilder entityBuilder = MultipartEntityBuilder.create();
    for (final Entry<String, ContentBody> part : post.entrySet())
        entityBuilder.addPart(part.getKey(), part.getValue());
    final HttpEntity multipartEntity = entityBuilder.build();
    // statistics
    this.upbytes = multipartEntity.getContentLength();

    if (usegzip) {
        httpPost.setEntity(new GzipCompressingEntity(multipartEntity));
    } else {
        httpPost.setEntity(multipartEntity);
    }

    if (!localhost || password == null) {
        return getContentBytes(httpPost, Integer.MAX_VALUE, concurrent);
    }

    byte[] content = null;

    final CredentialsProvider credsProvider = new BasicCredentialsProvider();
    credsProvider.setCredentials(new AuthScope("localhost", url.getPort()),
            new UsernamePasswordCredentials(userName, password));

    /* Use the custom YaCyDigestScheme for HTTP Digest Authentication */
    final Lookup<AuthSchemeProvider> authSchemeRegistry = RegistryBuilder.<AuthSchemeProvider>create()
            .register(AuthSchemes.BASIC, new BasicSchemeFactory())
            .register(AuthSchemes.DIGEST, new YaCyDigestSchemeFactory()).build();

    CloseableHttpClient httpclient = HttpClients.custom().setDefaultCredentialsProvider(credsProvider)
            .setDefaultAuthSchemeRegistry(authSchemeRegistry).build();

    try {
        this.httpResponse = httpclient.execute(httpPost);
        try {
            HttpEntity httpEntity = this.httpResponse.getEntity();
            if (httpEntity != null) {
                if (getStatusCode() == HttpStatus.SC_OK) {
                    content = getByteArray(httpEntity, Integer.MAX_VALUE);
                }
                // Ensures that the entity content is fully consumed and the content stream, if exists, is closed.
                EntityUtils.consume(httpEntity);
            }
        } finally {
            this.httpResponse.close();
        }
    } finally {
        httpclient.close();
    }
    return content;
}

From source file:com.evolveum.polygon.connector.ldap.ad.AdLdapConnector.java

private String getAuthenticationScheme() {
    if (getConfiguration().getWinRmAuthenticationScheme() == null) {
        return AuthSchemes.NTLM;
    }/*  w w  w  .j ava2s.  c o  m*/
    if (AdLdapConfiguration.WINDOWS_AUTHENTICATION_SCHEME_BASIC
            .equals(getConfiguration().getWinRmAuthenticationScheme())) {
        return AuthSchemes.BASIC;
    }
    if (AdLdapConfiguration.WINDOWS_AUTHENTICATION_SCHEME_NTLM
            .equals(getConfiguration().getWinRmAuthenticationScheme())) {
        return AuthSchemes.NTLM;
    }
    if (AdLdapConfiguration.WINDOWS_AUTHENTICATION_SCHEME_CREDSSP
            .equals(getConfiguration().getWinRmAuthenticationScheme())) {
        return AuthSchemes.CREDSSP;
    }
    throw new ConfigurationException(
            "Unknown authentication scheme: " + getConfiguration().getWinRmAuthenticationScheme());
}

From source file:org.apache.http.impl.client.AuthenticationStrategyImpl.java

protected boolean isCachable(final AuthScheme authScheme) {
    if (authScheme == null || !authScheme.isComplete()) {
        return false;
    }/*from   w  w w .  ja  v  a 2  s  .  c  o  m*/
    final String schemeName = authScheme.getSchemeName();
    return schemeName.equalsIgnoreCase(AuthSchemes.BASIC) || schemeName.equalsIgnoreCase(AuthSchemes.DIGEST);
}

From source file:org.jboss.as.test.integration.security.common.Utils.java

/**
 * Returns response body for the given URL request as a String. It also checks if the returned HTTP status code is the
 * expected one. If the server returns {@link HttpServletResponse#SC_UNAUTHORIZED} and username is provided, then a new
 * request is created with the provided credentials (basic authentication).
 *
 * @param url URL to which the request should be made
 * @param user Username (may be null)//from  w w w .  ja  v a 2s  . c o m
 * @param pass Password (may be null)
 * @param expectedStatusCode expected status code returned from the requested server
 * @param checkFollowupAuthState whether to check auth state for followup request - if set to true, followup
 *                               request is sent to server and 200 OK is expected directly (no re-authentication
 *                               challenge - 401 Unauthorized - is expected)
 * @return HTTP response body
 * @throws IOException
 * @throws URISyntaxException
 */
public static String makeCallWithBasicAuthn(URL url, String user, String pass, int expectedStatusCode,
        boolean checkFollowupAuthState) throws IOException, URISyntaxException {
    LOGGER.trace("Requesting URL " + url);

    // use UTF-8 charset for credentials
    Registry<AuthSchemeProvider> authSchemeRegistry = RegistryBuilder.<AuthSchemeProvider>create()
            .register(AuthSchemes.BASIC, new BasicSchemeFactory(Consts.UTF_8))
            .register(AuthSchemes.DIGEST, new DigestSchemeFactory(Consts.UTF_8)).build();
    try (final CloseableHttpClient httpClient = HttpClientBuilder.create()
            .setDefaultAuthSchemeRegistry(authSchemeRegistry).build()) {
        final HttpGet httpGet = new HttpGet(url.toURI());
        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());
        }
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("HTTP response was SC_UNAUTHORIZED, let's authenticate the user " + user);
        }
        HttpEntity entity = response.getEntity();
        if (entity != null)
            EntityUtils.consume(entity);

        final UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(user, pass);

        HttpClientContext hc = new HttpClientContext();
        hc.setCredentialsProvider(new BasicCredentialsProvider());
        hc.getCredentialsProvider().setCredentials(new AuthScope(url.getHost(), url.getPort()), credentials);
        //enable auth
        response = httpClient.execute(httpGet, hc);
        statusCode = response.getStatusLine().getStatusCode();
        assertEquals("Unexpected status code returned after the authentication.", expectedStatusCode,
                statusCode);

        if (checkFollowupAuthState) {
            // Let's disable authentication for this client as we already have all the context neccessary to be
            // authorized (we expect that gained 'nonce' value can be re-used in our case here).
            // By disabling authentication we simply get first server response and thus we can check whether we've
            // got 200 OK or different response code.
            RequestConfig reqConf = RequestConfig.custom().setAuthenticationEnabled(false).build();
            httpGet.setConfig(reqConf);
            response = httpClient.execute(httpGet, hc);
            statusCode = response.getStatusLine().getStatusCode();
            assertEquals("Unexpected status code returned after the authentication.", HttpURLConnection.HTTP_OK,
                    statusCode);
        }

        return EntityUtils.toString(response.getEntity());
    }
}

From source file:org.mitre.dsmiley.httpproxy.ProxyServlet.java

/**
 * Called from {@link #init(javax.servlet.ServletConfig)}. HttpClient offers
 * many opportunities for customization. By default, <a href=
 * "http://hc.apache.org/httpcomponents-client-ga/httpclient/apidocs/org/apache/http/impl/client/SystemDefaultHttpClient.html">
 * SystemDefaultHttpClient</a> is used if available, otherwise it falls back
 * to://ww  w . j a v  a2  s  .  com
 * 
 * <pre>
 * new DefaultHttpClient(new ThreadSafeClientConnManager(), hcParams)
 * </pre>
 * 
 * SystemDefaultHttpClient uses PoolingClientConnectionManager. In any case,
 * it should be thread-safe.
 */
protected HttpClient createHttpClient(HttpParams hcParams) {
    try {

        String negotiateURL = getConfigParam("negotiate.url");
        String negotiateSPN = getConfigParam("negotiate.spn");
        if (negotiateURL != null && negotiateSPN != null) {
            System.out.println("negotiate url:" + negotiateURL);
            System.out.println("negotiate spn:" + negotiateSPN);
            // initialize the Windows security Context to get the negotiate
            // client token
            IWindowsSecurityContext clientContext = null;
            IWindowsCredentialsHandle clientCredentials = null;
            clientContext = WindowsSecurityContextImpl.getCurrent(SECURITY_PACKAGE, negotiateSPN);
            clientCredentials = WindowsCredentialsHandleImpl.getCurrent(SECURITY_PACKAGE);
            clientCredentials.initialize();
            String username = WindowsAccountImpl.getCurrentUsername();
            System.out.println("credentials for user " + username + " get prepared");
            byte[] token = clientContext.getToken();
            // encode the token with Base64 to be able to add it to the http
            // header
            String clientToken = Base64.encodeBase64String(token);
            System.out.println("clientToken" + clientToken);
            // if there is only a negotiate url the rest of the
            // authorization is based on cookies
            // so we need to support them.
            CookieStore cookieStore = new BasicCookieStore();
            RequestConfig globalConfig = RequestConfig.custom().setCookieSpec(CookieSpecs.DEFAULT).build();
            HttpClientContext context = HttpClientContext.create();
            proxyContext = context;
            context.setCookieStore(cookieStore);
            HttpClient httpClient = HttpClients.custom().disableRedirectHandling()
                    .setDefaultRequestConfig(globalConfig).setDefaultCookieStore(cookieStore).build();

            // first we need to act as a normal browser to get a http 401
            // with negotiate header
            doActAsBrowser = true;
            HttpGet browserHttpGet = new HttpGet(negotiateURL);
            addBrowserHeader(browserHttpGet);
            HttpResponse rep = httpClient.execute(browserHttpGet, context);

            if (rep.getStatusLine().getStatusCode() == 401) {
                System.out.println("negotiate requested - sending negotiate client token");
                HttpGet negotiateHttpGet = new HttpGet(negotiateURL);
                addBrowserHeader(negotiateHttpGet);
                negotiateHttpGet.addHeader("Authorization", "Negotiate " + clientToken);
                HttpResponse response = httpClient.execute(negotiateHttpGet, context);
                System.out.println(
                        "http result code of negotiate request:" + response.getStatusLine().getStatusCode());
                // now the url needs to be called periodically to keep the
                // cookie and connection alive
                String refreshTimeString = getConfigParam("negotiate.refreshtime");
                long refreshTime = 1000000;
                if (refreshTimeString != null) {
                    refreshTime = Long.parseLong(refreshTimeString);
                }
                HttpClientRefreshThread thread = new HttpClientRefreshThread(refreshTime, negotiateURL);
                thread.start();
                List<org.apache.http.cookie.Cookie> cookies = context.getCookieStore().getCookies();
                cookieString = "";
                int size = cookies.size() - 1;
                for (int i = 0; i < cookies.size(); i++) {
                    cookieString += cookies.get(i).getName();
                    cookieString += "=";
                    cookieString += cookies.get(i).getValue();
                    if (i != size)
                        cookieString += "; ";
                }
            } else {
                System.out.println("No negotiate requested");
            }
        } else {
            if (!WinHttpClients.isWinAuthAvailable()) {
                System.out.println("Integrated Win auth is not supported!!!");
            } else {
                HttpClientBuilder builder = WinHttpClients.custom();
                Registry<AuthSchemeProvider> authSchemeRegistry = RegistryBuilder.<AuthSchemeProvider>create()
                        .register(AuthSchemes.BASIC, new BasicSchemeFactory())
                        .register(AuthSchemes.DIGEST, new DigestSchemeFactory())
                        .register(AuthSchemes.SPNEGO, new SPNegoSchemeFactory())
                        .register(AuthSchemes.NTLM, new NTLMSchemeFactory())
                        .register(AuthSchemes.KERBEROS, new KerberosSchemeFactory()).build();
                builder.setDefaultAuthSchemeRegistry(authSchemeRegistry);
                String username = getConfigParam("user");
                String password = getConfigParam("password");
                String domain = getConfigParam("domain");
                String host = getConfigParam("host");
                if (username != null) {
                    NTCredentials cred = new NTCredentials(username, password, host, domain);
                    CredentialsProvider credsProvider = new WindowsCredentialsProvider(
                            new SystemDefaultCredentialsProvider());
                    credsProvider.setCredentials(AuthScope.ANY, cred);
                    builder.setDefaultCredentialsProvider(credsProvider);
                }
                builder.disableCookieManagement();
                builder.disableRedirectHandling();
                return builder.build();
            }

            // as of HttpComponents v4.2, this class is better since it uses
            // System
            // Properties:
            Class<?> clientClazz = Class.forName("org.apache.http.impl.client.SystemDefaultHttpClient");
            Constructor<?> constructor = clientClazz.getConstructor(HttpParams.class);
            return (HttpClient) constructor.newInstance(hcParams);
        }
    } catch (ClassNotFoundException e) {
        // no problem; use v4.1 below
    } catch (Exception e) {
        throw new RuntimeException(e);
    }

    // Fallback on using older client:
    return new DefaultHttpClient(new ThreadSafeClientConnManager(), hcParams);
}