Example usage for org.apache.http.auth.params AuthPNames TARGET_AUTH_PREF

List of usage examples for org.apache.http.auth.params AuthPNames TARGET_AUTH_PREF

Introduction

In this page you can find the example usage for org.apache.http.auth.params AuthPNames TARGET_AUTH_PREF.

Prototype

String TARGET_AUTH_PREF

To view the source code for org.apache.http.auth.params AuthPNames TARGET_AUTH_PREF.

Click Source Link

Document

Defines the order of preference for supported org.apache.http.auth.AuthScheme s when authenticating with the target host.

Usage

From source file:nl.esciencecenter.octopus.webservice.JobLauncherService.java

/**
 * Adds MAC Access Authentication scheme to http client and registers list of MAC credentials with http client.
 *
 * Http client will use MAC Access Authentication when url is in scope of given MAC credentials.
 *
 * @param httpClient//from  ww w .  j  a  va 2s  .  co m
 * @param macs
 * @return httpClient with MAC access authentication and credentials injected.
 */
public static AbstractHttpClient macifyHttpClient(AbstractHttpClient httpClient,
        ImmutableList<MacCredential> macs) {

    // Add MAC scheme
    httpClient.getAuthSchemes().register(MacScheme.SCHEME_NAME, new MacSchemeFactory());

    // Add configured MAC id/key pairs.
    CredentialsProvider credentialProvider = httpClient.getCredentialsProvider();
    for (MacCredential mac : macs) {
        credentialProvider.setCredentials(mac.getAuthScope(), mac);
    }

    // Add MAC scheme to ordered list of supported authentication schemes
    // See HTTP authentication parameters chapter on
    // http://hc.apache.org/httpcomponents-client-ga/tutorial/html/authentication.html
    List<String> authSchemes = Collections.unmodifiableList(Arrays.asList(new String[] { MacScheme.SCHEME_NAME,
            AuthPolicy.SPNEGO, AuthPolicy.KERBEROS, AuthPolicy.NTLM, AuthPolicy.DIGEST, AuthPolicy.BASIC }));
    httpClient.getParams().setParameter(AuthPNames.TARGET_AUTH_PREF, authSchemes);

    return httpClient;
}

From source file:nl.esciencecenter.octopus.webservice.JobLauncherServiceTest.java

@Test
public void testMacifyHttpClient() throws URISyntaxException {
    // FIXME Waiting for https://github.com/NLeSC/octopus/issues/38 to be resolved
    JobLauncherConfiguration config = sampleConfiguration();
    DefaultHttpClient httpClient = new DefaultHttpClient();

    JobLauncherService.macifyHttpClient(httpClient, config.getMacs());

    assertTrue("MAC Registered auth scheme", httpClient.getAuthSchemes().getSchemeNames().contains("mac"));

    MacCredential expected_creds = config.getMacs().get(0);
    AuthScope authscope = expected_creds.getAuthScope();
    Credentials creds = httpClient.getCredentialsProvider().getCredentials(authscope);
    assertEquals(expected_creds, creds);

    List<String> authSchemes = Collections.unmodifiableList(Arrays.asList(new String[] { MacScheme.SCHEME_NAME,
            AuthPolicy.SPNEGO, AuthPolicy.KERBEROS, AuthPolicy.NTLM, AuthPolicy.DIGEST, AuthPolicy.BASIC }));
    assertEquals(authSchemes, httpClient.getParams().getParameter(AuthPNames.TARGET_AUTH_PREF));
}

From source file:ch.admin.hermes.etl.load.SharePoint2010RESTClient.java

/**
 * @throws IOException//from w w  w  .j av  a 2s.com
 */
private void init(String remote, String user, String pass) throws IOException {
    this.remote = (remote != null) ? remote : this.remote;
    this.user = (user != null) ? user : this.user;
    this.pass = (pass != null) ? pass : this.pass;

    client = getHttpClient();

    // localhost und domain nicht setzen, gibt Probleme mit https://
    NTCredentials creds = new NTCredentials(this.user, this.pass, "", "");
    client.getCredentialsProvider().setCredentials(AuthScope.ANY, creds);

    List<String> authpref = new ArrayList<String>();
    authpref.add(AuthPolicy.NTLM);
    client.getParams().setParameter(AuthPNames.TARGET_AUTH_PREF, authpref);
}

From source file:nl.esciencecenter.osmium.JobLauncherServiceTest.java

@Test
public void testMacifyHttpClient() throws URISyntaxException {
    // FIXME Waiting for https://github.com/NLeSC/xenon/issues/38 to be resolved
    JobLauncherConfiguration config = sampleConfiguration();
    DefaultHttpClient httpClient = new DefaultHttpClient();

    JobLauncherService.macifyHttpClient(httpClient, config.getMacs());

    assertTrue("MAC Registered auth scheme", httpClient.getAuthSchemes().getSchemeNames().contains("mac"));

    MacCredential expected_creds = config.getMacs().get(0);
    AuthScope authscope = expected_creds.getAuthScope();
    Credentials creds = httpClient.getCredentialsProvider().getCredentials(authscope);
    assertEquals(expected_creds, creds);

    List<String> authSchemes = Collections.unmodifiableList(Arrays.asList(new String[] { MacScheme.SCHEME_NAME,
            AuthPolicy.SPNEGO, AuthPolicy.KERBEROS, AuthPolicy.NTLM, AuthPolicy.DIGEST, AuthPolicy.BASIC }));
    assertEquals(authSchemes, httpClient.getParams().getParameter(AuthPNames.TARGET_AUTH_PREF));
}

From source file:ch.admin.hermes.etl.load.SharePointRESTClient.java

/**
 * @throws IOException/*from  w w w . ja  va 2 s  . c  om*/
 */
private void init(String remote, String user, String pass) throws IOException {
    this.remote = (remote != null) ? remote : this.remote;
    this.user = (user != null) ? user : this.user;
    this.pass = (pass != null) ? pass : this.pass;

    client = getHttpClient();

    // localhost und domain nicht setzen, gibt Probleme mit https://
    NTCredentials creds = new NTCredentials(this.user, this.pass, "", "");
    client.getCredentialsProvider().setCredentials(AuthScope.ANY, creds);

    List<String> authpref = new ArrayList<String>();
    authpref.add(AuthPolicy.NTLM);
    client.getParams().setParameter(AuthPNames.TARGET_AUTH_PREF, authpref);

    // FormDigestValue holen
    try {
        js = factory.getEngineByName("JavaScript");
        js.eval("function getId(rc) { print(rc); return(rc.d.GetContextWebInformation.FormDigestValue); }");

        String out = post("/_api/contextinfo", null);
        js.eval("var rc = " + out + ";");
        Object rc = js.get("rc");
        xRequestDigest = (String) ((Invocable) js).invokeFunction("getId", rc);
    } catch (NoSuchMethodException e) {
        throw new IOException(e);
    } catch (ScriptException e) {
        throw new IOException(e);
    }
}

From source file:org.obiba.opal.rest.client.magma.OpalJavaClient.java

private void createClient() {
    log.info("Connecting to Opal: {}", opalURI);
    DefaultHttpClient httpClient = new DefaultHttpClient();
    if (keyStore == null)
        httpClient.getCredentialsProvider().setCredentials(AuthScope.ANY, credentials);
    httpClient.getParams().setParameter(ClientPNames.HANDLE_AUTHENTICATION, Boolean.TRUE);
    httpClient.getParams().setParameter(AuthPNames.TARGET_AUTH_PREF,
            Collections.singletonList(OpalAuth.CREDENTIALS_HEADER));
    httpClient.getParams().setParameter(ClientPNames.CONNECTION_MANAGER_FACTORY_CLASS_NAME,
            OpalClientConnectionManagerFactory.class.getName());
    httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, connectionTimeout);
    httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, soTimeout);
    httpClient.setHttpRequestRetryHandler(new DefaultHttpRequestRetryHandler(DEFAULT_MAX_ATTEMPT, false));
    httpClient.getAuthSchemes().register(OpalAuth.CREDENTIALS_HEADER, new OpalAuthScheme.Factory());

    try {//from w  ww.  j a v a2s . co m
        httpClient.getConnectionManager().getSchemeRegistry()
                .register(new Scheme("https", HTTPS_PORT, getSocketFactory()));
    } catch (NoSuchAlgorithmException | KeyManagementException e) {
        throw new RuntimeException(e);
    }
    client = enableCaching(httpClient);

    ctx = new BasicHttpContext();
    ctx.setAttribute(ClientContext.COOKIE_STORE, new BasicCookieStore());
}

From source file:org.apache.abdera2.common.protocol.BasicClient.java

/**
 * When multiple authentication schemes are supported by a server, the client will automatically select a scheme
 * based on the configured priority. For instance, to tell the client to prefer "digest" over "basic", set the
 * priority by calling setAuthenticationSchemePriority("digest","basic")
 */// ww w  . j  a  va2s  .c o  m
public <T extends Client> T setAuthenticationSchemePriority(String... scheme) {
    List<?> authPrefs = java.util.Arrays.asList(scheme);
    client.getParams().setParameter(AuthPNames.TARGET_AUTH_PREF, authPrefs);
    return (T) this;
}

From source file:org.apache.abdera2.common.protocol.BasicClient.java

/**
 * Returns the current listing of preferred authentication schemes, in order of preference
 * //w w  w.  j  a v a  2s . c  o  m
 * @see setAuthenticationSchemePriority
 */
public String[] getAuthenticationSchemePriority() {
    List<?> list = (List<?>) client.getParams().getParameter(AuthPNames.TARGET_AUTH_PREF);
    return list.toArray(new String[list.size()]);
}

From source file:org.switchyard.component.http.OutboundHandler.java

/**
 * The handler method that invokes the actual HTTP service when the
 * component is used as a HTTP consumer.
 * @param exchange the Exchange//from ww  w  .j  a  va 2 s .  c  o  m
 * @throws HandlerException handler exception
 */
@Override
public void handleMessage(final Exchange exchange) throws HandlerException {
    // identify ourselves
    exchange.getContext().setProperty(ExchangeCompletionEvent.GATEWAY_NAME, _bindingName, Scope.EXCHANGE)
            .addLabels(BehaviorLabel.TRANSIENT.label());
    if (getState() != State.STARTED) {
        final String m = HttpMessages.MESSAGES.bindingNotStarted(_referenceName, _bindingName);
        LOGGER.error(m);
        throw new HandlerException(m);
    }

    HttpClient httpclient = new DefaultHttpClient();
    if (_timeout != null) {
        HttpParams httpParams = httpclient.getParams();
        HttpConnectionParams.setConnectionTimeout(httpParams, _timeout);
        HttpConnectionParams.setSoTimeout(httpParams, _timeout);
    }
    try {
        if (_credentials != null) {
            ((DefaultHttpClient) httpclient).getCredentialsProvider().setCredentials(_authScope, _credentials);
            List<String> authpref = new ArrayList<String>();
            authpref.add(AuthPolicy.NTLM);
            authpref.add(AuthPolicy.BASIC);
            httpclient.getParams().setParameter(AuthPNames.TARGET_AUTH_PREF, authpref);
        }
        if (_proxyHost != null) {
            httpclient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, _proxyHost);
        }
        HttpBindingData httpRequest = _messageComposer.decompose(exchange, new HttpRequestBindingData());
        HttpRequestBase request = null;
        if (_httpMethod.equals(HTTP_GET)) {
            request = new HttpGet(_baseAddress);
        } else if (_httpMethod.equals(HTTP_POST)) {
            request = new HttpPost(_baseAddress);
            ((HttpPost) request).setEntity(new BufferedHttpEntity(
                    new InputStreamEntity(httpRequest.getBodyBytes(), httpRequest.getBodyBytes().available())));
        } else if (_httpMethod.equals(HTTP_DELETE)) {
            request = new HttpDelete(_baseAddress);
        } else if (_httpMethod.equals(HTTP_HEAD)) {
            request = new HttpHead(_baseAddress);
        } else if (_httpMethod.equals(HTTP_PUT)) {
            request = new HttpPut(_baseAddress);
            ((HttpPut) request).setEntity(new BufferedHttpEntity(
                    new InputStreamEntity(httpRequest.getBodyBytes(), httpRequest.getBodyBytes().available())));
        } else if (_httpMethod.equals(HTTP_OPTIONS)) {
            request = new HttpOptions(_baseAddress);
        }
        Iterator<Map.Entry<String, List<String>>> entries = httpRequest.getHeaders().entrySet().iterator();
        while (entries.hasNext()) {
            Map.Entry<String, List<String>> entry = entries.next();
            String name = entry.getKey();
            if (REQUEST_HEADER_BLACKLIST.contains(name)) {
                HttpLogger.ROOT_LOGGER.removingProhibitedRequestHeader(name);
                continue;
            }
            List<String> values = entry.getValue();
            for (String value : values) {
                request.addHeader(name, value);
            }
        }
        if (_contentType != null) {
            request.addHeader("Content-Type", _contentType);
        }

        HttpResponse response = null;
        if ((_credentials != null) && (_credentials instanceof NTCredentials)) {
            // Send a request for the Negotiation
            response = httpclient.execute(new HttpGet(_baseAddress));
            HttpClientUtils.closeQuietly(response);
        }
        if (_authCache != null) {
            BasicHttpContext context = new BasicHttpContext();
            context.setAttribute(ClientContext.AUTH_CACHE, _authCache);
            response = httpclient.execute(request, context);
        } else {
            response = httpclient.execute(request);
        }
        int status = response.getStatusLine().getStatusCode();

        HttpEntity entity = response.getEntity();
        HttpResponseBindingData httpResponse = new HttpResponseBindingData();
        Header[] headers = response.getAllHeaders();
        for (Header header : headers) {
            httpResponse.addHeader(header.getName(), header.getValue());
        }
        if (entity != null) {
            if (entity.getContentType() != null) {
                httpResponse.setContentType(new ContentType(entity.getContentType().getValue()));
            } else {
                httpResponse.setContentType(new ContentType());
            }
            httpResponse.setBodyFromStream(entity.getContent());
        }
        httpResponse.setStatus(status);
        Message out = _messageComposer.compose(httpResponse, exchange);
        if (httpResponse.getStatus() < 400) {
            exchange.send(out);
        } else {
            exchange.sendFault(out);
        }
    } catch (Exception e) {
        final String m = HttpMessages.MESSAGES.unexpectedExceptionHandlingHTTPMessage();
        LOGGER.error(m, e);
        throw new HandlerException(m, e);
    } finally {
        // When HttpClient instance is no longer needed,
        // shut down the connection manager to ensure
        // immediate deallocation of all system resources
        httpclient.getConnectionManager().shutdown();
    }
}

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

/**
 * Build a new HTTP Client for the given parameters
 *
 * @param params//  ww w.  j  a  va 2  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;
}