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

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

Introduction

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

Prototype

public AuthScope(final String host, final int port) 

Source Link

Document

Creates a new credentials scope for the given host, port, any realm name, and any authentication scheme.

Usage

From source file:org.apache.cxf.fediz.integrationtests.HTTPTestUtils.java

public static String sendHttpGet(String url, String user, String password, int returnCodeIDP, int returnCodeRP,
        int idpPort) throws Exception {

    CloseableHttpClient httpClient = null;
    try {/*from w  w  w.ja va2  s.  c  om*/
        CredentialsProvider credsProvider = new BasicCredentialsProvider();
        credsProvider.setCredentials(new AuthScope("localhost", idpPort),
                new UsernamePasswordCredentials(user, password));

        KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
        FileInputStream instream = new FileInputStream(new File("./target/test-classes/client.jks"));
        try {
            trustStore.load(instream, "clientpass".toCharArray());
        } finally {
            try {
                instream.close();
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }

        SSLContextBuilder sslContextBuilder = new SSLContextBuilder();
        sslContextBuilder.loadTrustMaterial(trustStore, new TrustSelfSignedStrategy());
        sslContextBuilder.loadKeyMaterial(trustStore, "clientpass".toCharArray());

        SSLContext sslContext = sslContextBuilder.build();
        SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(sslContext);

        HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
        httpClientBuilder.setDefaultCredentialsProvider(credsProvider);
        httpClientBuilder.setSSLSocketFactory(sslSocketFactory);
        httpClientBuilder.setRedirectStrategy(new LaxRedirectStrategy());

        httpClient = httpClientBuilder.build();

        HttpGet httpget = new HttpGet(url);

        HttpResponse response = httpClient.execute(httpget);
        HttpEntity entity = response.getEntity();

        System.out.println(response.getStatusLine());
        if (entity != null) {
            System.out.println("Response content length: " + entity.getContentLength());
        }
        Assert.assertTrue("IDP HTTP Response code: " + response.getStatusLine().getStatusCode() + " [Expected: "
                + returnCodeIDP + "]", returnCodeIDP == response.getStatusLine().getStatusCode());

        if (response.getStatusLine().getStatusCode() != 200) {
            return null;
        }

        //            Redirect to a POST is not supported without user interaction
        //            http://www.ietf.org/rfc/rfc2616.txt
        //            If the 301 status code is received in response to a request other
        //            than GET or HEAD, the user agent MUST NOT automatically redirect the
        //            request unless it can be confirmed by the user, since this might
        //            change the conditions under which the request was issued.

        Source source = new Source(EntityUtils.toString(entity));
        List<NameValuePair> nvps = new ArrayList<NameValuePair>();
        FormFields formFields = source.getFormFields();

        List<Element> forms = source.getAllElements(HTMLElementName.FORM);
        Assert.assertEquals("Only one form expected but got " + forms.size(), 1, forms.size());
        String postUrl = forms.get(0).getAttributeValue("action");

        Assert.assertNotNull("Form field 'wa' not found", formFields.get("wa"));
        Assert.assertNotNull("Form field 'wresult' not found", formFields.get("wresult"));

        for (FormField formField : formFields) {
            if (formField.getUserValueCount() != 0) {
                nvps.add(new BasicNameValuePair(formField.getName(), formField.getValues().get(0)));
            }
        }
        HttpPost httppost = new HttpPost(postUrl);
        httppost.setEntity(new UrlEncodedFormEntity(nvps, Consts.UTF_8));

        response = httpClient.execute(httppost);

        entity = response.getEntity();
        System.out.println(response.getStatusLine());
        Assert.assertTrue("RP HTTP Response code: " + response.getStatusLine().getStatusCode() + " [Expected: "
                + returnCodeRP + "]", returnCodeRP == response.getStatusLine().getStatusCode());

        if (entity != null) {
            System.out.println("Response content length: " + entity.getContentLength());
        }

        return EntityUtils.toString(entity);
    } finally {
        // When HttpClient instance is no longer needed,
        // shut down the connection manager to ensure
        // immediate deallocation of all system resources
        if (httpClient != null) {
            httpClient.close();
        }
    }
}

From source file:org.artifactory.util.PreemptiveAuthInterceptor.java

@Override
public void process(HttpRequest request, HttpContext context) throws HttpException, IOException {
    HttpClientContext clientContext = HttpClientContext.adapt(context);
    AuthState authState = clientContext.getTargetAuthState();

    // If there's no auth scheme available yet, try to initialize it preemptively
    if (authState.getAuthScheme() == null) {
        CredentialsProvider credsProvider = clientContext.getCredentialsProvider();
        HttpHost targetHost = clientContext.getTargetHost();
        Credentials creds = credsProvider
                .getCredentials(new AuthScope(targetHost.getHostName(), targetHost.getPort()));
        if (creds == null) {
            log.debug("No credentials found for host " + targetHost);
        } else {//from w ww .j a  va 2  s.c o  m
            log.debug("Updating credentials for host " + targetHost);
            authState.update(new BasicScheme(), creds);
        }
    }
}

From source file:org.orbeon.oxf.resources.handler.PreemptiveAuthHttpRequestInterceptor.java

public void process(final HttpRequest request, final HttpContext context) throws HttpException, IOException {
    AuthState authState = (AuthState) context.getAttribute(ClientContext.TARGET_AUTH_STATE);
    CredentialsProvider credentialsProvider = (CredentialsProvider) context
            .getAttribute(ClientContext.CREDS_PROVIDER);
    HttpHost targetHost = (HttpHost) context.getAttribute(ExecutionContext.HTTP_TARGET_HOST);

    // If not auth scheme has been initialized yet
    if (authState.getAuthScheme() == null) {
        AuthScope authScope = new AuthScope(targetHost.getHostName(), targetHost.getPort());
        // Obtain credentials matching the target host
        Credentials credentials = credentialsProvider.getCredentials(authScope);
        // If found, generate BasicScheme preemptively
        if (credentials != null) {
            authState.setAuthScheme(credentials instanceof NTCredentials ? new NTLMScheme(new JCIFSEngine())
                    : new BasicScheme());
            authState.setCredentials(credentials);
        }/*from w w  w.j a  v  a  2s  . co  m*/
    }
}

From source file:org.sonatype.nexus.httpclient.PreemptiveAuthHttpRequestInterceptor.java

@Override
public void process(final HttpRequest request, final HttpContext context) throws HttpException, IOException {
    HttpClientContext clientContext = HttpClientContext.adapt(context);
    AuthState authState = clientContext.getTargetAuthState();
    if (authState.getAuthScheme() == null) {
        CredentialsProvider credsProvider = clientContext.getCredentialsProvider();
        HttpHost targetHost = clientContext.getTargetHost();
        Credentials creds = credsProvider
                .getCredentials(new AuthScope(targetHost.getHostName(), targetHost.getPort()));
        if (creds != null) {
            authState.update(new BasicScheme(), creds);
        }/*from  ww w.  j a  va  2  s  .c om*/
    }
}

From source file:org.commonjava.maven.galley.transport.htcli.internal.TLLocationCredentialsProvider.java

public synchronized void bind(final Collection<HttpLocation> locations) {
    if (locations != null) {
        final Map<AuthScope, Credentials> creds = new HashMap<AuthScope, Credentials>();
        final Map<AuthScope, HttpLocation> repos = new HashMap<AuthScope, HttpLocation>();
        for (final HttpLocation location : locations) {
            final AuthScope as = new AuthScope(location.getHost(), location.getPort());
            //                logger.info( "Storing repository def: {} under authscope: {}:{}", repository.getName(),
            //                             repository.getHost(), repository.getPort() );

            //TODO: Seems like multiple repos with same host/port could easily cause confusion if they're not configured the same way later on...
            repos.put(as, location);/*from  ww w  .jav a2s.  c o  m*/

            if (location.getUser() != null) {
                creds.put(as, new UsernamePasswordCredentials(location.getUser(),
                        passwordManager.getPassword(new PasswordEntry(location, PasswordEntry.USER_PASSWORD))));
            }

            if (location.getProxyHost() != null && location.getProxyUser() != null) {
                creds.put(new AuthScope(location.getProxyHost(), location.getProxyPort()),
                        new UsernamePasswordCredentials(location.getProxyUser(), passwordManager
                                .getPassword(new PasswordEntry(location, PasswordEntry.PROXY_PASSWORD))));
            }
        }

        this.credentials.set(creds);
        this.repositories.set(repos);
    }
}

From source file:com.ibm.watson.developer_cloud.retrieve_and_rank.v1.utils.HttpSolrClientUtils.java

/**
 * Creates the {@link HttpClient} to use with the Solrj
 *
 * @param url the Solr server url//from w ww  . j  av a  2s  .c  o  m
 * @param username the {@link RetrieveAndRank} service username
 * @param password the {@link RetrieveAndRank} service password
 * @return the {@link HttpClient}
 */
public static HttpClient createHttpClient(String url, String username, String password) {
    URI scopeUri = URI.create(url);

    BasicCredentialsProvider credentialsProvider = new BasicCredentialsProvider();
    credentialsProvider.setCredentials(new AuthScope(scopeUri.getHost(), scopeUri.getPort()),
            new UsernamePasswordCredentials(username, password));

    HttpClientBuilder builder = HttpClientBuilder.create().setMaxConnTotal(128).setMaxConnPerRoute(32)
            .setDefaultRequestConfig(
                    RequestConfig.copy(RequestConfig.DEFAULT).setRedirectsEnabled(true).build())
            .setDefaultCredentialsProvider(credentialsProvider)
            .addInterceptorFirst(new PreemptiveAuthInterceptor());
    return builder.build();
}

From source file:cn.edu.pku.lib.dataverse.doi.DataCiteRESTfullClient.java

public DataCiteRESTfullClient(String url, String username, String password) {
    this.url = url;
    try {//w ww  .j av a  2s .  com
        context = HttpClientContext.create();
        CredentialsProvider credsProvider = new BasicCredentialsProvider();
        credsProvider.setCredentials(new AuthScope(null, -1),
                new UsernamePasswordCredentials(username, password));
        context.setCredentialsProvider(credsProvider);

        httpClient = HttpClients.createDefault();
    } catch (Exception ioe) {
        close();
        logger.log(Level.SEVERE, "Fail to init Client", ioe);
        throw new RuntimeException("Fail to init Client", ioe);
    }
}

From source file:de.unikassel.android.sdcframework.transmission.BasicAuthHttpProtocol.java

@Override
protected final void configureForAuthentication(DefaultHttpClient client, URL url) {
    client.getCredentialsProvider().setCredentials(new AuthScope(url.getHost(), -1),
            new UsernamePasswordCredentials(getUserName(), getMd5Password()));
}

From source file:com.amazonaws.eclipse.core.HttpClientFactory.java

private static void configureProxy(DefaultHttpClient client, String url) {
    AwsToolkitCore plugin = AwsToolkitCore.getDefault();
    if (plugin != null) {
        IProxyService proxyService = AwsToolkitCore.getDefault().getProxyService();

        if (proxyService.isProxiesEnabled()) {
            try {
                IProxyData[] proxyData;/* w  w  w.  j  a  va  2 s.  co m*/
                proxyData = proxyService.select(new URI(url));
                if (proxyData.length > 0) {

                    IProxyData data = proxyData[0];
                    client.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY,
                            new HttpHost(data.getHost(), data.getPort()));

                    if (data.isRequiresAuthentication()) {
                        client.getCredentialsProvider().setCredentials(
                                new AuthScope(data.getHost(), data.getPort()),
                                new NTCredentials(data.getUserId(), data.getPassword(), null, null));
                    }
                }
            } catch (URISyntaxException e) {
                plugin.getLog().log(new Status(Status.ERROR, AwsToolkitCore.PLUGIN_ID, e.getMessage(), e));
            }
        }
    }
}

From source file:com.cisco.cta.taxii.adapter.httpclient.CredentialsProviderFactory.java

private void addProxyCredentials(CredentialsProvider credsProvider) {
    if (proxySettings.getUrl() == null) {
        return;//from  w  w  w .  ja va  2s  . c o  m
    }
    if (proxySettings.getAuthenticationType() == null) {
        throw new IllegalStateException("Both proxy url and proxy authentication type have to be specified.");
    }

    ProxyAuthenticationType authType = proxySettings.getAuthenticationType();

    URL proxyUrl = proxySettings.getUrl();
    HttpHost proxyHost = new HttpHost(proxyUrl.getHost(), proxyUrl.getPort(), proxyUrl.getProtocol());

    Credentials credentials;
    switch (authType) {
    case NONE:
        break;

    case BASIC:
        credentials = new UsernamePasswordCredentials(proxySettings.getUsername(), proxySettings.getPassword());
        credsProvider.setCredentials(new AuthScope(proxyHost.getHostName(), proxyHost.getPort()), credentials);
        break;

    case NTLM:
        credentials = new NTCredentials(proxySettings.getUsername(), proxySettings.getPassword(),
                proxySettings.getWorkstation(), proxySettings.getDomain());
        credsProvider.setCredentials(new AuthScope(proxyHost.getHostName(), proxyHost.getPort()), credentials);
        break;

    default:
        throw new IllegalStateException("Unsupported authentication type: " + authType);
    }
}