Example usage for org.apache.http.impl.auth BasicSchemeFactory BasicSchemeFactory

List of usage examples for org.apache.http.impl.auth BasicSchemeFactory BasicSchemeFactory

Introduction

In this page you can find the example usage for org.apache.http.impl.auth BasicSchemeFactory BasicSchemeFactory.

Prototype

public BasicSchemeFactory() 

Source Link

Usage

From source file:org.brunocvcunha.taskerbox.core.http.TaskerboxHttpBox.java

/**
 * Build a new HTTP Client for the given parameters
 *
 * @param params/* w w w  . j a v  a2 s.  c  o  m*/
 * @return
 */
public DefaultHttpClient buildNewHttpClient(HttpParams params) {
    PoolingClientConnectionManager cxMgr = new PoolingClientConnectionManager(
            SchemeRegistryFactory.createDefault());
    cxMgr.setMaxTotal(100);
    cxMgr.setDefaultMaxPerRoute(20);

    DefaultHttpClient httpClient = new DefaultHttpClient(cxMgr, params);
    httpClient.getParams().setParameter(CoreProtocolPNames.USER_AGENT,
            "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/40.0.2214.111 Safari/537.36");
    // httpClient.getParams().setParameter(ClientPNames.COOKIE_POLICY,
    // CookiePolicy.BROWSER_COMPATIBILITY);
    if (this.useNtlm) {
        httpClient.getAuthSchemes().register("NTLM", new NTLMSchemeFactory());
        httpClient.getAuthSchemes().register("BASIC", new BasicSchemeFactory());
        httpClient.getAuthSchemes().register("DIGEST", new DigestSchemeFactory());
        httpClient.getAuthSchemes().register("SPNEGO", new SPNegoSchemeFactory());
        httpClient.getAuthSchemes().register("KERBEROS", new KerberosSchemeFactory());
    }

    try {
        SSLContext sc = SSLContext.getInstance("SSL");
        sc.init(null, getTrustingManager(), new java.security.SecureRandom());
        SSLSocketFactory socketFactory = new SSLSocketFactory(sc);
        Scheme sch = new Scheme("https", 443, socketFactory);
        httpClient.getConnectionManager().getSchemeRegistry().register(sch);
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    } catch (KeyManagementException e) {
        e.printStackTrace();
    }

    if (this.useProxy) {
        if (this.proxySocks) {

            log.info("Using proxy socks " + this.socksHost + ":" + this.socksPort);

            System.setProperty("socksProxyHost", this.socksHost);
            System.setProperty("socksProxyPort", String.valueOf(this.socksPort));

        } else {
            HttpHost proxy = new HttpHost(this.proxyHost, this.proxyPort);
            httpClient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);

            if (this.authProxy) {

                List<String> authPreferences = new ArrayList<>();

                if (this.ntlmProxy) {

                    NTCredentials creds = new NTCredentials(this.proxyUser, this.proxyPassword,
                            this.proxyWorkstation, this.proxyDomain);
                    httpClient.getCredentialsProvider()
                            .setCredentials(new AuthScope(this.proxyHost, this.proxyPort), creds);
                    // httpClient.getCredentialsProvider().setCredentials(
                    // AuthScope.ANY, creds);

                    authPreferences.add(AuthPolicy.NTLM);
                } else {
                    UsernamePasswordCredentials creds = new UsernamePasswordCredentials(this.proxyUser,
                            this.proxyPassword);
                    httpClient.getCredentialsProvider().setCredentials(AuthScope.ANY, creds);

                    authPreferences.add(AuthPolicy.BASIC);
                }

                httpClient.getParams().setParameter(AuthPNames.TARGET_AUTH_PREF, authPreferences);
            }
        }

    }

    return httpClient;
}

From source file:org.apache.calcite.avatica.remote.AvaticaCommonsHttpClientImpl.java

@Override
public void setUsernamePassword(AuthenticationType authType, String username, String password) {
    this.credentials = new UsernamePasswordCredentials(Objects.requireNonNull(username),
            Objects.requireNonNull(password));

    this.credentialsProvider = new BasicCredentialsProvider();
    credentialsProvider.setCredentials(AuthScope.ANY, credentials);

    RegistryBuilder<AuthSchemeProvider> authRegistryBuilder = RegistryBuilder.create();
    switch (authType) {
    case BASIC:/*from  ww  w  .j  a  va2  s . c o m*/
        authRegistryBuilder.register(AuthSchemes.BASIC, new BasicSchemeFactory());
        break;
    case DIGEST:
        authRegistryBuilder.register(AuthSchemes.DIGEST, new DigestSchemeFactory());
        break;
    default:
        throw new IllegalArgumentException("Unsupported authentiation type: " + authType);
    }
    this.authRegistry = authRegistryBuilder.build();
}

From source file:plugins.KerberosSsoTest.java

/**
 * HTTP client that does not negotiate.//from   w  ww .jav a2 s  . c  o m
 */
// I am not able to get the basic auth to work in FF 45.3.0, so using HttpClient instead
// org.openqa.selenium.UnsupportedCommandException: Unrecognized command: POST /session/466a800f-eaf8-40cf-a9e8-815f5a6e3c32/alert/credentials
// alert.setCredentials(new UserAndPassword("user", "ATH"));
private CloseableHttpClient getBadassHttpClient() {
    return HttpClientBuilder.create().setDefaultAuthSchemeRegistry(RegistryBuilder.<AuthSchemeProvider>create()
            .register(AuthSchemes.BASIC, new BasicSchemeFactory()).build()).build();
}

From source file:org.apache.maven.wagon.providers.http.AbstractHttpClientWagonFixed.java

private static CloseableHttpClient createClient() {
    return HttpClientBuilder.create() //
            .useSystemProperties() //
            .disableConnectionState() //
            .setConnectionManager(httpClientConnectionManager) //
            //Using Custom Default Schema Registry
            .setDefaultAuthSchemeRegistry(RegistryBuilder.<AuthSchemeProvider>create()
                    .register(AuthSchemes.BASIC, new BasicSchemeFactory())
                    .register(AuthSchemes.DIGEST, new DigestSchemeFactory())
                    .register(AuthSchemes.NTLM, new NTLMSchemeFactory())
                    //Using Custom SPNEGO Factory & FORCE strip port
                    //Kerberos Error: Server not found in Kerberos database (7) - LOOKING_UP_SERVER
                    .register(AuthSchemes.SPNEGO, new SPNegoSchemeFactory(true))
                    .register(AuthSchemes.KERBEROS, new KerberosSchemeFactory(true)).build())
            .build();/*from   w  w  w  . j a v  a  2  s  .  c o  m*/
}

From source file:com.mirth.connect.connectors.ws.WebServiceDispatcher.java

/**
 * Returns the URL for the passed in String. If the URL requires authentication, then the WSDL
 * is saved as a temp file and the URL for that file is returned.
 * //  w w w.  j  a v a  2s  . com
 * @param wsdlUrl
 * @param username
 * @param password
 * @return
 * @throws Exception
 */
private URL getWsdlUrl(DispatchContainer dispatchContainer) throws Exception {
    URI uri = new URI(dispatchContainer.getCurrentWsdlUrl());

    // If the URL points to file, just return it
    if (!uri.getScheme().equalsIgnoreCase("file")) {
        BasicHttpClientConnectionManager httpClientConnectionManager = new BasicHttpClientConnectionManager(
                socketFactoryRegistry.build());
        httpClientConnectionManager.setSocketConfig(SocketConfig.custom().setSoTimeout(timeout).build());
        HttpClientBuilder clientBuilder = HttpClients.custom()
                .setConnectionManager(httpClientConnectionManager);
        HttpUtil.configureClientBuilder(clientBuilder);
        CloseableHttpClient client = clientBuilder.build();

        try {
            clients.add(client);
            HttpClientContext context = HttpClientContext.create();

            if (dispatchContainer.getCurrentUsername() != null
                    && dispatchContainer.getCurrentPassword() != null) {
                CredentialsProvider credsProvider = new BasicCredentialsProvider();
                AuthScope authScope = new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT,
                        AuthScope.ANY_REALM);
                Credentials credentials = new UsernamePasswordCredentials(
                        dispatchContainer.getCurrentUsername(), dispatchContainer.getCurrentPassword());
                credsProvider.setCredentials(authScope, credentials);
                AuthCache authCache = new BasicAuthCache();
                RegistryBuilder<AuthSchemeProvider> registryBuilder = RegistryBuilder
                        .<AuthSchemeProvider>create();
                registryBuilder.register(AuthSchemes.BASIC, new BasicSchemeFactory());

                context.setCredentialsProvider(credsProvider);
                context.setAuthSchemeRegistry(registryBuilder.build());
                context.setAuthCache(authCache);
            }

            RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(timeout)
                    .setSocketTimeout(timeout).setStaleConnectionCheckEnabled(true).build();
            context.setRequestConfig(requestConfig);

            return getWsdl(client, context, dispatchContainer, new HashMap<String, File>(),
                    dispatchContainer.getCurrentWsdlUrl()).toURI().toURL();
        } finally {
            HttpClientUtils.closeQuietly(client);
            clients.remove(client);
        }
    }

    return uri.toURL();
}

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

/**
 * This method GETs a page from the server.
 *
 * @param uri the url to get/*  www.  jav  a2  s.c  o m*/
 * @param username user name for HTTP authentication : only sent requesting localhost
 * @param pass password for HTTP authentication : only sent when requesting localhost
 * @param maxBytes maximum response bytes to read
 * @param concurrent whether a new thread should be created to handle the request. 
 * Ignored when requesting localhost or when the authentication password is not null
 * @return content bytes
 * @throws IOException
 */
public byte[] GETbytes(final MultiProtocolURL url, final String username, final String pass, final int maxBytes,
        final boolean concurrent) throws IOException {
    final boolean localhost = Domains.isLocalhost(url.getHost());
    final String urix = url.toNormalform(true);
    HttpGet httpGet = null;
    try {
        httpGet = new HttpGet(urix);
    } catch (IllegalArgumentException e) {
        throw new IOException(e.getMessage()); // can be caused  at java.net.URI.create()
    }
    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 (!localhost || pass == null) {
        return getContentBytes(httpGet, maxBytes, concurrent);
    }

    CredentialsProvider credsProvider = new BasicCredentialsProvider();
    credsProvider.setCredentials(new AuthScope("localhost", url.getPort()),
            new UsernamePasswordCredentials(username, pass));

    /* 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();
    byte[] content = null;
    try {
        this.httpResponse = httpclient.execute(httpGet);
        try {
            HttpEntity httpEntity = this.httpResponse.getEntity();
            if (httpEntity != null) {
                if (getStatusCode() == HttpStatus.SC_OK) {
                    if (maxBytes >= 0 && httpEntity.getContentLength() > maxBytes) {
                        /* When anticipated content length is already known and exceed the specified limit : 
                         * throw an exception and abort the connection, consistently with getByteArray() implementation 
                         * Otherwise returning null and consuming fully the entity can be very long on large resources */
                        throw new IOException("Content to download exceed maximum value of "
                                + Formatter.bytesToString(maxBytes));
                    }
                    content = getByteArray(httpEntity, maxBytes);
                }
                // Ensures that the entity content is fully consumed and the content stream, if exists, is closed.
                EntityUtils.consume(httpEntity);
            }
        } catch (final IOException e) {
            httpGet.abort();
            throw e;
        } finally {
            this.httpResponse.close();
        }
    } finally {
        httpclient.close();
    }
    return content;
}

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//  w  ww. ja va 2  s . c om
 * @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:org.apache.http.impl.client.AbstractHttpClient.java

protected AuthSchemeRegistry createAuthSchemeRegistry() {
    final AuthSchemeRegistry registry = new AuthSchemeRegistry();
    registry.register(AuthPolicy.BASIC, new BasicSchemeFactory());
    registry.register(AuthPolicy.DIGEST, new DigestSchemeFactory());
    registry.register(AuthPolicy.NTLM, new NTLMSchemeFactory());
    registry.register(AuthPolicy.SPNEGO, new SPNegoSchemeFactory());
    registry.register(AuthPolicy.KERBEROS, new KerberosSchemeFactory());
    return registry;
}

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

protected AuthSchemeRegistry createAuthSchemeRegistry() {
    AuthSchemeRegistry registry = new AuthSchemeRegistry();
    registry.register(AuthPolicy.BASIC, new BasicSchemeFactory());
    registry.register(AuthPolicy.DIGEST, new DigestSchemeFactory());
    registry.register(AuthPolicy.NTLM, new NTLMSchemeFactory());
    registry.register(AuthPolicy.SPNEGO, new NegotiateSchemeFactory());
    return registry;
}

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://from   w  w  w  .j  ava  2 s.  c o m
 * 
 * <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);
}