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.modeshape.web.jcr.rest.client.http.HttpClientConnection.java

/**
 * @param server the server with the host and port information (never <code>null</code>)
 * @param url the URL that will be used in the request (never <code>null</code>)
 * @param method the HTTP request method (never <code>null</code>)
 * @throws Exception if there is a problem establishing the connection
 *///  ww  w.j  a v  a  2s. c  om
public HttpClientConnection(Server server, URL url, RequestMethod method) throws Exception {
    assert server != null;
    assert url != null;
    assert method != null;

    this.httpClient = new DefaultHttpClient();
    this.httpClient.getCredentialsProvider().setCredentials(new AuthScope(url.getHost(), url.getPort()),
            new UsernamePasswordCredentials(server.getUser(), server.getPassword()));
    // determine the request type
    if (RequestMethod.GET == method) {
        this.request = new HttpGet();
    } else if (RequestMethod.DELETE == method) {
        this.request = new HttpDelete();
    } else if (RequestMethod.POST == method) {
        this.request = new HttpPost();
    } else if (RequestMethod.PUT == method) {
        this.request = new HttpPut();
    } else {
        throw new RuntimeException(unknownHttpRequestMethodMsg.text(method));
    }

    //set the accepts header to application/json
    this.request.setHeader("Accept", MediaType.APPLICATION_JSON);

    // set request URI
    this.request.setURI(url.toURI());
}

From source file:org.sonatype.nexus.testsuite.security.nexus4383.Nexus4383LogoutResourceIT.java

/**
 * 1.) Make a get request to set a cookie </BR>
 * 2.) verify cookie works (do not send basic auth) </BR>
 * 3.) do logout  </BR>//from   w  w w  . j  a  v  a2 s .  com
 * 4.) repeat step 2 and expect failure.
 */
@Test
public void testLogout() throws Exception {
    TestContext context = TestContainer.getInstance().getTestContext();
    String username = context.getAdminUsername();
    String password = context.getPassword();
    String url = this.getBaseNexusUrl() + RequestFacade.SERVICE_LOCAL + "status";
    String logoutUrl = this.getBaseNexusUrl() + RequestFacade.SERVICE_LOCAL + "authentication/logout";

    Header userAgentHeader = new BasicHeader("User-Agent", "Something Stateful");

    // default useragent is: Jakarta Commons-HttpClient/3.1[\r][\n]
    DefaultHttpClient httpClient = new DefaultHttpClient();
    URI nexusBaseURI = new URI(url);
    final BasicHttpContext localcontext = new BasicHttpContext();
    final HttpHost targetHost = new HttpHost(nexusBaseURI.getHost(), nexusBaseURI.getPort(),
            nexusBaseURI.getScheme());
    httpClient.getCredentialsProvider().setCredentials(
            new AuthScope(targetHost.getHostName(), targetHost.getPort()),
            new UsernamePasswordCredentials(username, password));
    AuthCache authCache = new BasicAuthCache();
    BasicScheme basicAuth = new BasicScheme();
    authCache.put(targetHost, basicAuth);
    localcontext.setAttribute(ClientContext.AUTH_CACHE, authCache);

    // HACK: Disable CSRFGuard support for now, its too problematic
    //String owaspQueryParams = null;
    HttpGet getMethod = new HttpGet(url);
    getMethod.addHeader(userAgentHeader);
    try {
        CloseableHttpResponse response = httpClient.execute(getMethod, localcontext);
        // HACK: Disable CSRFGuard support for now, its too problematic
        //Header owaspCsrfToken = response.getFirstHeader("OWASP_CSRFTOKEN");
        //assertThat(owaspCsrfToken, is(notNullValue()));
        //owaspQueryParams = "?" + owaspCsrfToken.getName() + "=" + owaspCsrfToken.getValue();
        Assert.assertEquals(response.getStatusLine().getStatusCode(), 200);
    } finally {
        getMethod.reset();
    }

    Cookie sessionCookie = this.getSessionCookie(httpClient.getCookieStore().getCookies());
    Assert.assertNotNull("Session Cookie not set", sessionCookie);

    httpClient.getCookieStore().clear(); // remove cookies
    httpClient.getCredentialsProvider().clear(); // remove auth

    // now with just the cookie
    httpClient.getCookieStore().addCookie(sessionCookie);
    // HACK: Disable CSRFGuard support for now, its too problematic
    //getMethod = new HttpGet(url + owaspQueryParams);
    getMethod = new HttpGet(url);
    try {
        Assert.assertEquals(httpClient.execute(getMethod).getStatusLine().getStatusCode(), 200);
    } finally {
        getMethod.reset();
    }

    // do logout
    // HACK: Disable CSRFGuard support for now, its too problematic
    //HttpGet logoutGetMethod = new HttpGet(logoutUrl + owaspQueryParams);
    HttpGet logoutGetMethod = new HttpGet(logoutUrl);
    try {
        final HttpResponse response = httpClient.execute(logoutGetMethod);
        Assert.assertEquals(response.getStatusLine().getStatusCode(), 200);
        Assert.assertEquals("OK", EntityUtils.toString(response.getEntity()));
    } finally {
        logoutGetMethod.reset();
    }

    // set cookie again
    httpClient.getCookieStore().clear(); // remove cookies
    httpClient.getCredentialsProvider().clear(); // remove auth

    httpClient.getCookieStore().addCookie(sessionCookie);
    HttpGet failedGetMethod = new HttpGet(url);
    try {
        final HttpResponse response = httpClient.execute(failedGetMethod);
        Assert.assertEquals(response.getStatusLine().getStatusCode(), 401);
    } finally {
        failedGetMethod.reset();
    }
}

From source file:devza.app.android.droidnetkey.UsageAction.java

@Override
protected String[] doInBackground(String... arg0) {
    AuthScope scope = new AuthScope("maties2.sun.ac.za", 443);
    Credentials mCredentials = new UsernamePasswordCredentials(arg0[0], arg0[1]);
    CredentialsProvider mProvider = new BasicCredentialsProvider();
    mProvider.setCredentials(scope, mCredentials);
    ((AbstractHttpClient) this.client).setCredentialsProvider(mProvider);

    HttpGet fwusage = new HttpGet(FW_URL);

    String response;//from  w  w w . j  a  va 2  s .c o m

    try {
        response = getResponse(fwusage);
    } catch (SocketTimeoutException e) {
        // TODO Auto-generated catch block
        return null;
    } catch (ClientProtocolException e) {
        // TODO Auto-generated catch block
        return null;
    } catch (IOException e) {
        // TODO Auto-generated catch block
        return null;
    }

    response = response.replace("\r\n", "");

    //<td align="right"><font size="1">(.*)</font></td> ([0-9\\.]+)
    Pattern pattern = Pattern.compile(
            "<td><font size=\"1\"><strong>Total</strong></font></td>    <td align=\"right\"><font size=\"1\">([0-9\\.]+)</font></td>    <td align=\"right\"><font size=\"1\">([0-9\\.]+)</font></td>");
    Matcher matcher = pattern.matcher(response);

    String[] out = new String[2];

    if (matcher.find()) {
        out[0] = matcher.group(1);
        out[1] = matcher.group(2);
    }

    return out;

}

From source file:com.liferay.jsonwebserviceclient.JSONWebServiceClientImpl.java

public void afterPropertiesSet() {
    HttpClientBuilder httpClientBuilder = HttpClients.custom();

    httpClientBuilder.setConnectionManager(getPoolingHttpClientConnectionManager());

    if ((_login != null) && (_password != null)) {
        CredentialsProvider credentialsProvider = new BasicCredentialsProvider();

        credentialsProvider.setCredentials(new AuthScope(_hostName, _hostPort),
                new UsernamePasswordCredentials(_login, _password));

        httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider);
        httpClientBuilder.setRetryHandler(new HttpRequestRetryHandlerImpl());
    } else {//from   w w w.j av  a2  s .co  m
        if (_logger.isWarnEnabled()) {
            _logger.warn("Login and password are required");
        }
    }

    try {
        setProxyHost(httpClientBuilder);

        _closeableHttpClient = httpClientBuilder.build();

        if (_logger.isDebugEnabled()) {
            _logger.debug("Configured client for " + _protocol + "://" + _hostName);
        }
    } catch (Exception e) {
        _logger.error("Unable to configure client", e);
    }
}

From source file:org.gradle.api.internal.artifacts.repositories.transport.http.HttpClientConfigurer.java

private void useCredentials(DefaultHttpClient httpClient, PasswordCredentials credentials, String host,
        int port) {
    Credentials basicCredentials = new UsernamePasswordCredentials(credentials.getUsername(),
            credentials.getPassword());//from  www . ja  v  a2 s.co m
    httpClient.getCredentialsProvider().setCredentials(new AuthScope(host, port), basicCredentials);

    NTLMCredentials ntlmCredentials = new NTLMCredentials(credentials);
    Credentials ntCredentials = new NTCredentials(ntlmCredentials.getUsername(), ntlmCredentials.getPassword(),
            ntlmCredentials.getWorkstation(), ntlmCredentials.getDomain());
    httpClient.getCredentialsProvider()
            .setCredentials(new AuthScope(host, port, AuthScope.ANY_REALM, AuthPolicy.NTLM), ntCredentials);

    LOGGER.debug("Using {} and {} for authenticating against '{}:{}'",
            new Object[] { credentials, ntlmCredentials, host, port });
}

From source file:org.kaaproject.kaa.server.appenders.rest.appender.RestLogAppender.java

@Override
protected void initFromConfiguration(LogAppenderDto appender, RestConfig configuration) {
    this.configuration = configuration;
    this.executor = Executors.newFixedThreadPool(configuration.getConnectionPoolSize());
    target = new HttpHost(configuration.getHost(), configuration.getPort(),
            configuration.getSsl() ? "https" : "http");
    HttpClientBuilder builder = HttpClients.custom();
    if (configuration.getUsername() != null && configuration.getPassword() != null) {
        LOG.info("Adding basic auth credentials provider");
        CredentialsProvider credsProvider = new BasicCredentialsProvider();
        credsProvider.setCredentials(new AuthScope(target.getHostName(), target.getPort()),
                new UsernamePasswordCredentials(configuration.getUsername(), configuration.getPassword()));
        builder.setDefaultCredentialsProvider(credsProvider);
    }/*from   ww  w .  j  a v  a 2 s.c o  m*/
    if (!configuration.getVerifySslCert()) {
        LOG.info("Adding trustful ssl context");
        SSLContextBuilder sslBuilder = new SSLContextBuilder();
        try {
            sslBuilder.loadTrustMaterial(null, new TrustSelfSignedStrategy());
            SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslBuilder.build());
            builder.setSSLSocketFactory(sslsf);
        } catch (NoSuchAlgorithmException | KeyStoreException | KeyManagementException ex) {
            LOG.error("Failed to init socket factory {}", ex.getMessage(), ex);
        }
    }
    PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager();
    cm.setDefaultMaxPerRoute(configuration.getConnectionPoolSize());
    cm.setMaxTotal(configuration.getConnectionPoolSize());
    builder.setConnectionManager(cm);
    this.client = builder.build();
}

From source file:org.picketbox.test.authentication.http.jetty.DelegatingSecurityFilterHTTPBasicUnitTestCase.java

@Test
public void testBasicAuth() throws Exception {
    URL url = new URL(urlStr);

    DefaultHttpClient httpclient = null;
    try {//from   w ww  .ja  v  a  2 s .c  o m
        String user = "Aladdin";
        String pass = "Open Sesame";

        httpclient = new DefaultHttpClient();
        httpclient.getCredentialsProvider().setCredentials(new AuthScope(url.getHost(), url.getPort()),
                new UsernamePasswordCredentials(user, pass));

        HttpGet httpget = new HttpGet(url.toExternalForm());

        System.out.println("executing request" + httpget.getRequestLine());
        HttpResponse response = httpclient.execute(httpget);
        HttpEntity entity = response.getEntity();

        System.out.println("----------------------------------------");
        StatusLine statusLine = response.getStatusLine();
        System.out.println(statusLine);
        if (entity != null) {
            System.out.println("Response content length: " + entity.getContentLength());
        }
        assertEquals(200, statusLine.getStatusCode());
        EntityUtils.consume(entity);
    } 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:com.logsniffer.settings.http.HttpSettings.java

/**
 * Creates a {@link HttpClientBuilder} considering current settings.
 * /*from   w  w  w  . jav  a2s. c om*/
 * @return a {@link HttpClientBuilder} considering current settings.
 */
public HttpClientBuilder createHttpClientBuilder() {
    HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
    if (getHttpProxy() != null && StringUtils.isNotBlank(getHttpProxy().getHost())) {
        httpClientBuilder = httpClientBuilder.setProxy(
                new HttpHost(getHttpProxy().getHost(), getHttpProxy().getPort(), getHttpProxy().getSchema()));
        if (StringUtils.isNotBlank(getHttpProxy().getUser())) {
            Credentials credentials = new UsernamePasswordCredentials(getHttpProxy().getUser(),
                    getHttpProxy().getPassword());
            AuthScope authScope = new AuthScope(getHttpProxy().getHost(), getHttpProxy().getPort());
            CredentialsProvider credsProvider = new BasicCredentialsProvider();
            credsProvider.setCredentials(authScope, credentials);
            httpClientBuilder = httpClientBuilder.setDefaultCredentialsProvider(credsProvider);
            httpClientBuilder.useSystemProperties();
        }
    }
    return httpClientBuilder;
}

From source file:org.openrepose.commons.utils.http.ServiceClient.java

private HttpClient getClientWithBasicAuth() throws ServiceClientException {
    HttpClientResponse clientResponse = null;

    try {/*from w w w  . j av a2s . c o m*/

        clientResponse = httpClientService.getClient(connectionPoolId);
        final HttpClient client = clientResponse.getHttpClient();

        if (!StringUtilities.isEmpty(targetHostUri) && !StringUtilities.isEmpty(username)
                && !StringUtilities.isEmpty(password)) {

            client.getParams().setParameter(AuthPNames.PROXY_AUTH_PREF, AuthPolicy.BASIC);

            CredentialsProvider credsProvider = new BasicCredentialsProvider();

            credsProvider.setCredentials(new AuthScope(targetHostUri, AuthScope.ANY_PORT),
                    new UsernamePasswordCredentials(username, password));
            client.getParams().setParameter("http.authentication.credential-provider", credsProvider);

        }

        return client;

    } catch (HttpClientNotFoundException e) {
        LOG.error("Failed to obtain an HTTP default client connection");
        throw new ServiceClientException("Failed to obtain an HTTP default client connection", e);
    } finally {
        if (clientResponse != null) {
            httpClientService.releaseClient(clientResponse);
        }
    }

}

From source file:org.guvnor.ala.wildfly.access.WildflyClient.java

public int deploy(File file) throws WildflyClientException {

    // the digest auth backend
    CredentialsProvider credsProvider = new BasicCredentialsProvider();
    credsProvider.setCredentials(new AuthScope(host, managementPort),
            new UsernamePasswordCredentials(user, password));

    CloseableHttpClient httpclient = custom().setDefaultCredentialsProvider(credsProvider).build();

    HttpPost post = new HttpPost("http://" + host + ":" + managementPort + "/management-upload");

    post.addHeader("X-Management-Client-Name", "HAL");

    // the file to be uploaded
    FileBody fileBody = new FileBody(file);

    // the DMR operation
    ModelNode operation = new ModelNode();
    operation.get("address").add("deployment", file.getName());
    operation.get("operation").set("add");
    operation.get("runtime-name").set(file.getName());
    operation.get("enabled").set(true);
    operation.get("content").add().get("input-stream-index").set(0); // point to the multipart index used

    ByteArrayOutputStream bout = new ByteArrayOutputStream();
    try {/*ww  w.  jav  a  2s .  co m*/
        operation.writeBase64(bout);
    } catch (IOException ex) {
        getLogger(WildflyClient.class.getName()).log(SEVERE, null, ex);
    }

    // the multipart
    MultipartEntityBuilder builder = create();
    builder.setMode(BROWSER_COMPATIBLE);
    builder.addPart("uploadFormElement", fileBody);
    builder.addPart("operation",
            new ByteArrayBody(bout.toByteArray(), create("application/dmr-encoded"), "blob"));
    HttpEntity entity = builder.build();

    post.setEntity(entity);

    try {
        HttpResponse response = httpclient.execute(post);
        int statusCode = response.getStatusLine().getStatusCode();
        if (statusCode != 200) {
            throw new WildflyClientException("Error Deploying App Status Code: " + statusCode);
        }
        return statusCode;
    } catch (IOException ex) {
        LOG.error("Error Deploying App : " + ex.getMessage(), ex);
        throw new WildflyClientException("Error Deploying App : " + ex.getMessage(), ex);
    }
}