Example usage for org.apache.http.auth AuthScope ANY

List of usage examples for org.apache.http.auth AuthScope ANY

Introduction

In this page you can find the example usage for org.apache.http.auth AuthScope ANY.

Prototype

AuthScope ANY

To view the source code for org.apache.http.auth AuthScope ANY.

Click Source Link

Document

Default scope matching any host, port, realm and authentication scheme.

Usage

From source file:com.netscape.certsrv.client.PKIConnection.java

public PKIConnection(ClientConfig config) {

    this.config = config;

    // Register https scheme.
    Scheme scheme = new Scheme("https", 443, new JSSProtocolSocketFactory());
    httpClient.getConnectionManager().getSchemeRegistry().register(scheme);

    // Don't retry operations.
    httpClient.setHttpRequestRetryHandler(new DefaultHttpRequestRetryHandler(0, false));

    if (config.getUsername() != null && config.getPassword() != null) {
        List<String> authPref = new ArrayList<String>();
        authPref.add(AuthPolicy.BASIC);/* ww w. j a v a  2s  .  co  m*/
        httpClient.getParams().setParameter(AuthPNames.PROXY_AUTH_PREF, authPref);

        httpClient.getCredentialsProvider().setCredentials(AuthScope.ANY,
                new UsernamePasswordCredentials(config.getUsername(), config.getPassword()));
    }

    httpClient.addRequestInterceptor(new HttpRequestInterceptor() {
        @Override
        public void process(HttpRequest request, HttpContext context) throws HttpException, IOException {

            requestCounter++;

            if (verbose) {
                System.out.println("HTTP request: " + request.getRequestLine());
                for (Header header : request.getAllHeaders()) {
                    System.out.println("  " + header.getName() + ": " + header.getValue());
                }
            }

            if (output != null) {
                File file = new File(output, "http-request-" + requestCounter);
                storeRequest(file, request);
            }

            // Set the request parameter to follow redirections.
            HttpParams params = request.getParams();
            if (params instanceof ClientParamsStack) {
                ClientParamsStack paramsStack = (ClientParamsStack) request.getParams();
                params = paramsStack.getRequestParams();
            }
            HttpClientParams.setRedirecting(params, true);
        }
    });

    httpClient.addResponseInterceptor(new HttpResponseInterceptor() {
        @Override
        public void process(HttpResponse response, HttpContext context) throws HttpException, IOException {

            responseCounter++;

            if (verbose) {
                System.out.println("HTTP response: " + response.getStatusLine());
                for (Header header : response.getAllHeaders()) {
                    System.out.println("  " + header.getName() + ": " + header.getValue());
                }
            }

            if (output != null) {
                File file = new File(output, "http-response-" + responseCounter);
                storeResponse(file, response);
            }
        }
    });

    httpClient.setRedirectStrategy(new DefaultRedirectStrategy() {
        @Override
        public HttpUriRequest getRedirect(HttpRequest request, HttpResponse response, HttpContext context)
                throws ProtocolException {

            HttpUriRequest uriRequest = super.getRedirect(request, response, context);

            URI uri = uriRequest.getURI();
            if (verbose)
                System.out.println("HTTP redirect: " + uri);

            // Redirect the original request to the new URI.
            RequestWrapper wrapper;
            if (request instanceof HttpEntityEnclosingRequest) {
                wrapper = new EntityEnclosingRequestWrapper((HttpEntityEnclosingRequest) request);
            } else {
                wrapper = new RequestWrapper(request);
            }
            wrapper.setURI(uri);

            return wrapper;
        }

        @Override
        public boolean isRedirected(HttpRequest request, HttpResponse response, HttpContext context)
                throws ProtocolException {

            // The default redirection policy does not redirect POST or PUT.
            // This overrides the policy to follow redirections for all HTTP methods.
            return response.getStatusLine().getStatusCode() == 302;
        }
    });

    engine = new ApacheHttpClient4Engine(httpClient);

    resteasyClient = new ResteasyClientBuilder().httpEngine(engine).build();
    resteasyClient.register(PKIRESTProvider.class);
}

From source file:org.springframework.mobile.urbanairship.impl.UrbanAirshipTemplate.java

private RestTemplate createRestTemplate(String key, String secret) {
    HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory();
    DefaultHttpClient httpClient = new DefaultHttpClient();
    BasicCredentialsProvider credentialsProvider = new BasicCredentialsProvider();
    credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(key, secret));
    httpClient.setCredentialsProvider(credentialsProvider);
    requestFactory.setHttpClient(httpClient);
    return new RestTemplate(requestFactory);
}

From source file:org.opencastproject.remotetest.server.DigestAuthenticationTest.java

@Test
public void testDigestAuthenticatedPost() throws Exception {
    DefaultHttpClient httpclient = new DefaultHttpClient();

    // Perform a HEAD, and extract the realm and nonce
    HttpHead head = new HttpHead(BASE_URL);
    head.addHeader("X-Requested-Auth", "Digest");
    HttpResponse headResponse = httpclient.execute(head);
    Header authHeader = headResponse.getHeaders("WWW-Authenticate")[0];
    String nonce = null;//from   w  ww.j  a  v a2 s  . c om
    String realm = null;
    for (HeaderElement element : authHeader.getElements()) {
        if ("nonce".equals(element.getName())) {
            nonce = element.getValue();
        } else if ("Digest realm".equals(element.getName())) {
            realm = element.getValue();
        }
    }
    // Build the post
    UsernamePasswordCredentials creds = new UsernamePasswordCredentials("matterhorn_system_account",
            "CHANGE_ME");
    HttpPost post = new HttpPost(BASE_URL + "/capture-admin/agents/testagent");
    post.addHeader("X-Requested-Auth", "Digest");
    httpclient.getCredentialsProvider().setCredentials(AuthScope.ANY, creds);
    List<BasicNameValuePair> params = new ArrayList<BasicNameValuePair>();
    params.add(new BasicNameValuePair("state", "idle"));
    UrlEncodedFormEntity entity = new UrlEncodedFormEntity(params, "UTF-8");
    post.setEntity(entity);

    // Add the previously obtained nonce
    HttpContext localContext = new BasicHttpContext();
    DigestScheme digestAuth = new DigestScheme();
    digestAuth.overrideParamter("realm", realm);
    digestAuth.overrideParamter("nonce", nonce);
    localContext.setAttribute("preemptive-auth", digestAuth);

    // Send the POST
    try {
        HttpResponse response = httpclient.execute(post, localContext);
        String content = IOUtils.toString(response.getEntity().getContent(), "UTF-8");
        Assert.assertEquals(HttpStatus.SC_OK, response.getStatusLine().getStatusCode());
        Assert.assertEquals("testagent set to idle", content);
    } finally {
        httpclient.getConnectionManager().shutdown();
    }
}

From source file:org.zaizi.manifoldcf.authorities.authorities.alfresco.AlfrescoAuthorityConnector.java

/**
 * Connect.//from   w w  w  . j a  v a  2 s .c om
 * 
 * @param configParams is the set of configuration parameters, which in this case describe the target appliance,
 *            basic auth configuration, etc. (This formerly came out of the ini file.)
 */
@Override
public void connect(ConfigParams configParams) {
    super.connect(configParams);
    username = params.getParameter(AlfrescoConfig.USERNAME_PARAM);
    password = params.getObfuscatedParameter(AlfrescoConfig.PASSWORD_PARAM);
    protocol = params.getParameter(AlfrescoConfig.PROTOCOL_PARAM);
    server = params.getParameter(AlfrescoConfig.SERVER_PARAM);
    port = params.getParameter(AlfrescoConfig.PORT_PARAM);
    path = params.getParameter(AlfrescoConfig.PATH_PARAM);

    PoolingClientConnectionManager connectionManager = new PoolingClientConnectionManager();
    httpClient = new DefaultHttpClient(connectionManager);
    UsernamePasswordCredentials creds = new UsernamePasswordCredentials(username, password);
    httpClient.getCredentialsProvider().setCredentials(AuthScope.ANY, creds);
}

From source file:com.sun.jersey.client.apache4.impl.AuthTest.java

public void testPreemptiveAuthPost() {
    ResourceConfig rc = new DefaultResourceConfig(PreemptiveAuthResource.class);
    rc.getProperties().put(ResourceConfig.PROPERTY_CONTAINER_REQUEST_FILTERS, LoggingFilter.class.getName());
    startServer(rc);//  w w  w  . ja  v a  2s  . co m

    CredentialsProvider credentialsProvider = new org.apache.http.impl.client.BasicCredentialsProvider();
    credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials("name", "password"));

    DefaultApacheHttpClient4Config config = new DefaultApacheHttpClient4Config();
    config.getProperties().put(ApacheHttpClient4Config.PROPERTY_CREDENTIALS_PROVIDER, credentialsProvider);

    config.getProperties().put(ApacheHttpClient4Config.PROPERTY_PREEMPTIVE_BASIC_AUTHENTICATION, true);

    ApacheHttpClient4 c = ApacheHttpClient4.create(config);

    WebResource r = c.resource(getUri().build());
    assertEquals("POST", r.post(String.class, "POST"));
}

From source file:org.muhia.app.psi.integ.config.ke.shared.SharedWsClientConfiguration.java

@Bean(name = "sharedSecureHttpClient")
public CloseableHttpClient secureHttpClient() {
    CloseableHttpClient httpClient = HttpClientBuilder.create().build();
    try {/*from www . j  a  v a2  s  . c  om*/
        /*
        TODO: Modify to accept only specific certificates, test implementation is as below,
        TODO: need to find a way of determining if server url is https or not
        TODO: Whether we have imported the certificate or not
        */
        KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
        Resource resource = loaderService.getResource(properties.getSharedKeystorePath());
        keyStore.load(resource.getInputStream(),
                hasher.getDecryptedValue(properties.getSharedKeystorePassword()).toCharArray());
        SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustSelfSignedStrategy())
                .loadKeyMaterial(keyStore,
                        hasher.getDecryptedValue(properties.getSharedKeystorePassword()).toCharArray())
                .build();
        //            SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, (certificate, authType) -> true).build();

        RequestConfig config = RequestConfig.custom()
                .setConnectTimeout(properties.getSharedTransportConnectionTimeout())
                .setConnectionRequestTimeout(properties.getSharedTransportConnectionRequestTimeout())
                .setSocketTimeout(properties.getSharedTransportReadTimeout()).build();
        CredentialsProvider provider = new BasicCredentialsProvider();
        UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(
                sharedDataDTO.getTransportUsername(), sharedDataDTO.getTransportPassword());
        provider.setCredentials(AuthScope.ANY, credentials);

        PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager();
        connManager.setMaxTotal(properties.getSharedPoolMaxHost());
        connManager.setDefaultMaxPerRoute(properties.getSharedPoolDefaultmaxPerhost());
        connManager.setValidateAfterInactivity(properties.getSharedPoolValidateAfterInactivity());
        httpClient = HttpClientBuilder.create().setSSLContext(sslContext)
                .setSSLHostnameVerifier(new NoopHostnameVerifier()).setDefaultRequestConfig(config)
                .setDefaultCredentialsProvider(provider).setConnectionManager(connManager)
                .evictExpiredConnections().addInterceptorFirst(new RemoveHttpHeadersInterceptor()).build();
    } catch (NoSuchAlgorithmException | KeyStoreException | KeyManagementException | CertificateException
            | IOException | UnrecoverableKeyException e) {
        Logger.getLogger(this.getClass().getName()).log(Level.SEVERE, e.getMessage(), e);
    }
    return httpClient;

}

From source file:com.microsoft.alm.plugin.context.ServerContext.java

protected static ClientConfig getClientConfig(final Type type, final AuthenticationInfo authenticationInfo,
        final boolean includeProxySettings) {
    final Credentials credentials = AuthHelper.getCredentials(type, authenticationInfo);

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

    final ConnectorProvider connectorProvider = new ApacheConnectorProvider();

    final ClientConfig clientConfig = new ClientConfig().connectorProvider(connectorProvider);
    clientConfig.property(ApacheClientProperties.CREDENTIALS_PROVIDER, credentialsProvider);

    clientConfig.property(ApacheClientProperties.PREEMPTIVE_BASIC_AUTHENTICATION, true);
    clientConfig.property(ClientProperties.REQUEST_ENTITY_PROCESSING, RequestEntityProcessing.BUFFERED);

    //Define a local HTTP proxy
    if (includeProxySettings) {
        final String proxyHost;
        if (System.getProperty("proxyHost") != null) {
            proxyHost = System.getProperty("proxyHost");
        } else {/*from   w  w  w.  j av a  2  s  .com*/
            proxyHost = "127.0.0.1";
        }

        final String proxyPort;
        if (System.getProperty("proxyPort") != null) {
            proxyPort = System.getProperty("proxyPort");
        } else {
            proxyPort = "8888";
        }

        final String proxyUrl = String.format("http://%s:%s", proxyHost, proxyPort);

        clientConfig.property(ClientProperties.PROXY_URI, proxyUrl);
    }

    // if this is a onPrem server and the uri starts with https, we need to setup ssl
    if (isSSLEnabledOnPrem(type, authenticationInfo.getServerUri())) {
        clientConfig.property(ApacheClientProperties.SSL_CONFIG, getSslConfigurator());
    }

    return clientConfig;
}

From source file:org.sonatype.nexus.examples.url.UrlRealmTest.java

@Test(expected = UnknownAccountException.class)
public void testAuthcWrongCreds() throws Exception {
    // build client
    BasicCredentialsProvider credsProvider = new BasicCredentialsProvider();
    credsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(username, "cake"));
    httpClient = HttpClients.custom().setDefaultCredentialsProvider(credsProvider).build();
    when(hc4Provider.createHttpClient(Mockito.any(RemoteStorageContext.class))).thenReturn(httpClient);

    urlRealm.getAuthenticationInfo(new UsernamePasswordToken(username, "cake"));
}

From source file:microsoft.exchange.webservices.data.HttpClientWebRequest.java

/**
 * Prepare connection//  w ww.ja  v a 2s .c o m
 *
 * @throws microsoft.exchange.webservices.data.EWSHttpException the eWS http exception
 */
@Override
public void prepareConnection() throws EWSHttpException {
    try {
        HttpClientBuilder builder = HttpClients.custom();
        builder.setConnectionManager(this.httpClientConnMng);

        //create the cookie store
        if (cookieStore == null) {
            cookieStore = new BasicCookieStore();
        }
        builder.setDefaultCookieStore(cookieStore);

        if (getProxy() != null) {
            HttpHost proxy = new HttpHost(getProxy().getHost(), getProxy().getPort());
            builder.setProxy(proxy);

            if (HttpProxyCredentials.isProxySet()) {
                NTCredentials cred = new NTCredentials(HttpProxyCredentials.getUserName(),
                        HttpProxyCredentials.getPassword(), "", HttpProxyCredentials.getDomain());
                CredentialsProvider credsProvider = new BasicCredentialsProvider();
                credsProvider.setCredentials(new AuthScope(proxy), cred);
                builder.setDefaultCredentialsProvider(credsProvider);
            }
        }
        if (getUserName() != null) {
            CredentialsProvider credsProvider = new BasicCredentialsProvider();
            credsProvider.setCredentials(AuthScope.ANY,
                    new NTCredentials(getUserName(), getPassword(), "", getDomain()));
            builder.setDefaultCredentialsProvider(credsProvider);
        }

        //fix socket config
        SocketConfig sc = SocketConfig.custom().setSoTimeout(getTimeout()).build();
        builder.setDefaultSocketConfig(sc);

        RequestConfig.Builder rcBuilder = RequestConfig.custom();
        rcBuilder.setAuthenticationEnabled(true);
        rcBuilder.setConnectionRequestTimeout(getTimeout());
        rcBuilder.setConnectTimeout(getTimeout());
        rcBuilder.setRedirectsEnabled(isAllowAutoRedirect());
        rcBuilder.setSocketTimeout(getTimeout());

        // fix issue #144 + #160: if we used NTCredentials from above: these are NT credentials
        if (getUserName() != null) {
            ArrayList<String> authPrefs = new ArrayList<String>();
            authPrefs.add(AuthSchemes.NTLM);
            rcBuilder.setTargetPreferredAuthSchemes(authPrefs);
        }
        //
        builder.setDefaultRequestConfig(rcBuilder.build());

        httpPostReq = new HttpPost(getUrl().toString());
        httpPostReq.addHeader("Content-type", getContentType());
        //httpPostReq.setDoAuthentication(true);
        httpPostReq.addHeader("User-Agent", getUserAgent());
        httpPostReq.addHeader("Accept", getAccept());
        httpPostReq.addHeader("Keep-Alive", "300");
        httpPostReq.addHeader("Connection", "Keep-Alive");

        if (isAcceptGzipEncoding()) {
            httpPostReq.addHeader("Accept-Encoding", "gzip,deflate");
        }

        if (getHeaders().size() > 0) {
            for (Map.Entry<String, String> httpHeader : getHeaders().entrySet()) {
                httpPostReq.addHeader(httpHeader.getKey(), httpHeader.getValue());
            }
        }

        //create the client
        client = builder.build();
    } catch (Exception er) {
        er.printStackTrace();
    }
}