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

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

Introduction

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

Prototype

public BasicScheme() 

Source Link

Usage

From source file:com.cloudhopper.httpclient.util.HttpSender.java

static public Response postXml(String url, String username, String password, String requestXml)
        throws Exception {
    ///*from   w w w.j ava2s . c  o m*/
    // trust any SSL connection
    //
    TrustManager easyTrustManager = new X509TrustManager() {
        public void checkClientTrusted(java.security.cert.X509Certificate[] arg0, String arg1)
                throws CertificateException {
            // allow all
        }

        public void checkServerTrusted(java.security.cert.X509Certificate[] arg0, String arg1)
                throws CertificateException {
            // allow all
        }

        public java.security.cert.X509Certificate[] getAcceptedIssuers() {
            return null;
        }
    };

    Scheme http = new Scheme("http", PlainSocketFactory.getSocketFactory(), 80);
    SSLContext sslcontext = SSLContext.getInstance("TLS");
    sslcontext.init(null, new TrustManager[] { easyTrustManager }, null);
    SSLSocketFactory sf = new SSLSocketFactory(sslcontext);
    sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
    Scheme https = new Scheme("https", sf, 443);

    //SchemeRegistry sr = new SchemeRegistry();
    //sr.register(http);
    //sr.register(https);

    // create and initialize scheme registry
    //SchemeRegistry schemeRegistry = new SchemeRegistry();
    //schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));

    // create an HttpClient with the ThreadSafeClientConnManager.
    // This connection manager must be used if more than one thread will
    // be using the HttpClient.
    //ThreadSafeClientConnManager cm = new ThreadSafeClientConnManager(schemeRegistry);
    //cm.setMaxTotalConnections(1);

    DefaultHttpClient client = new DefaultHttpClient();

    client.getConnectionManager().getSchemeRegistry().register(https);

    HttpPost post = new HttpPost(url);

    StringEntity postEntity = new StringEntity(requestXml, "ISO-8859-1");
    postEntity.setContentType("text/xml; charset=\"ISO-8859-1\"");
    post.addHeader("SOAPAction", "\"\"");
    post.setEntity(postEntity);

    long start = System.currentTimeMillis();

    client.getCredentialsProvider().setCredentials(new AuthScope(null, AuthScope.ANY_PORT),
            new UsernamePasswordCredentials(username, password));

    BasicHttpContext localcontext = new BasicHttpContext();

    // Generate BASIC scheme object and stick it to the local
    // execution context
    BasicScheme basicAuth = new BasicScheme();
    localcontext.setAttribute("preemptive-auth", basicAuth);

    // Add as the first request interceptor
    client.addRequestInterceptor(new PreemptiveAuth(), 0);

    HttpResponse httpResponse = client.execute(post, localcontext);
    HttpEntity responseEntity = httpResponse.getEntity();

    Response rsp = new Response();

    // set the status line and reason
    rsp.statusCode = httpResponse.getStatusLine().getStatusCode();
    rsp.statusLine = httpResponse.getStatusLine().getReasonPhrase();

    // get an input stream
    rsp.body = EntityUtils.toString(responseEntity);

    // When HttpClient instance is no longer needed,
    // shut down the connection manager to ensure
    // immediate deallocation of all system resources
    client.getConnectionManager().shutdown();

    return rsp;
}

From source file:com.ksc.http.apache.utils.ApacheUtils.java

private static void addPreemptiveAuthenticationProxy(HttpClientContext clientContext,
        HttpClientSettings settings) {//from w w  w . j a v a 2s .  c o m

    if (settings.isPreemptiveBasicProxyAuth()) {
        HttpHost targetHost = new HttpHost(settings.getProxyHost(), settings.getProxyPort());
        final CredentialsProvider credsProvider = newProxyCredentialsProvider(settings);
        // Create AuthCache instance
        AuthCache authCache = new BasicAuthCache();
        // Generate BASIC scheme object and add it to the local auth cache
        BasicScheme basicAuth = new BasicScheme();
        authCache.put(targetHost, basicAuth);

        clientContext.setCredentialsProvider(credsProvider);
        clientContext.setAuthCache(authCache);
    }
}

From source file:org.mobicents.servlet.restcomm.fax.InterfaxService.java

private URI send(final Object message) throws Exception {
    final FaxRequest request = (FaxRequest) message;
    final String to = request.to();
    final File file = request.file();
    // Prepare the request.
    final DefaultHttpClient client = new DefaultHttpClient();
    final HttpContext context = new BasicHttpContext();
    final SSLSocketFactory sockets = new SSLSocketFactory(strategy);
    final Scheme scheme = new Scheme("https", 443, sockets);
    client.getConnectionManager().getSchemeRegistry().register(scheme);
    final UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(user, password);
    final HttpPost post = new HttpPost(url + to);
    final String mime = URLConnection.guessContentTypeFromName(file.getName());
    final FileEntity entity = new FileEntity(file, mime);
    post.addHeader(new BasicScheme().authenticate(credentials, post, context));
    post.setEntity(entity);//from  w w w  . ja v a  2  s. c o m
    // Handle the response.
    final HttpResponse response = client.execute(post, context);
    final StatusLine status = response.getStatusLine();
    final int code = status.getStatusCode();
    if (HttpStatus.SC_CREATED == code) {
        EntityUtils.consume(response.getEntity());
        final Header[] headers = response.getHeaders(HttpHeaders.LOCATION);
        final Header location = headers[0];
        final String resource = location.getValue();
        return URI.create(resource);
    } else {
        final StringBuilder buffer = new StringBuilder();
        buffer.append(code).append(" ").append(status.getReasonPhrase());
        throw new FaxServiceException(buffer.toString());
    }
}

From source file:org.xwiki.contrib.jira.macro.internal.source.HTTPJIRAFetcher.java

private void setPreemptiveBasicAuthentication(HttpClientContext context, JIRAServer jiraServer,
        HttpHost targetHost) {/*from w w  w .  j a v a  2s.  c  o m*/
    // Connect to JIRA using basic authentication if username and password are defined
    // Note: Set up preemptive basic authentication since JIRA can accept both unauthenticated and authenticated
    // requests. See https://developer.atlassian.com/server/jira/platform/basic-authentication/
    if (StringUtils.isNotBlank(jiraServer.getUsername()) && StringUtils.isNotBlank(jiraServer.getPassword())) {
        CredentialsProvider provider = new BasicCredentialsProvider();
        provider.setCredentials(new AuthScope(targetHost.getHostName(), targetHost.getPort()),
                new UsernamePasswordCredentials(jiraServer.getUsername(), jiraServer.getPassword()));
        // Create AuthCache instance
        AuthCache authCache = new BasicAuthCache();
        // Generate BASIC scheme object and add it to the local auth cache
        BasicScheme basicAuth = new BasicScheme();
        authCache.put(targetHost, basicAuth);
        // Add AuthCache to the execution context
        context.setCredentialsProvider(provider);
        context.setAuthCache(authCache);
    }
}

From source file:org.apache.syncope.installer.utilities.HttpUtils.java

public int getWithBasicAuth(final String path) {
    final HttpGet httpGet;
    if (isSsl) {//from  w  w  w .  j a va 2s .  c om
        httpGet = new HttpGet(String.format(HTTPS_URL_TEMPLATE, host, port) + path);
    } else {
        httpGet = new HttpGet(String.format(HTTP_URL_TEMPLATE, host, port) + path);
    }
    int status = 0;
    handler.logOutput("Calling " + httpGet.getURI(), true);
    InstallLog.getInstance().info("Calling " + httpGet.getURI());
    try {
        try (CloseableHttpResponse response = httpClient.execute(targetHost, httpGet,
                setAuth(targetHost, new BasicScheme()))) {

            status = response.getStatusLine().getStatusCode();
            handler.logOutput("Calling status " + status, true);
            InstallLog.getInstance().info("Calling status " + status);
        }
    } catch (IOException e) {
        String messageError = "Error in " + path + ": " + e.getMessage();
        handler.emitError(messageError, messageError);
        InstallLog.getInstance().error(messageError);
    }
    return status;
}

From source file:org.sonatype.spice.zapper.client.hc4.Hc4Client.java

@Override
public State upload(final Payload payload, final Hc4Track track) throws IOException {
    final String url = getRemoteUrl() + payload.getPath().stringValue();
    final HttpPut put = new HttpPut(url);
    if (payload instanceof SegmentPayload) {
        put.setEntity(new ZapperEntity(payload, getParameters().getCodecSelector()
                .selectCodecs(SegmentPayload.class.cast(payload).getSegment().getZFile())));
    } else {//from  w  ww  .  j av a  2  s .co m
        put.setEntity(new ZapperEntity(payload));
    }
    put.addHeader("X-Zapper-Transfer-ID", payload.getTransferIdentifier().stringValue());
    if (track != null) {
        put.addHeader("X-Zapper-Track-ID", track.getIdentifier().stringValue());
    }
    final HttpClientContext context = new HttpClientContext();
    if (preemptiveCredentialsProvider != null) {
        context.setCredentialsProvider(preemptiveCredentialsProvider);
        context.setAuthCache(new BasicAuthCache());
        context.getAuthCache().put(
                new HttpHost(put.getURI().getHost(), put.getURI().getPort(), put.getURI().getScheme()),
                new BasicScheme());
    }
    final HttpResponse response = httpClient.execute(put, context);
    final StatusLine statusLine = response.getStatusLine();
    EntityUtils.consume(response.getEntity());
    if (!(statusLine.getStatusCode() > 199 && statusLine.getStatusCode() < 299)) {
        throw new IOException(String.format("Unexpected server response: %s %s", statusLine.getStatusCode(),
                statusLine.getReasonPhrase()));
    }
    return State.SUCCESS;
}

From source file:org.jfrog.build.client.PreemptiveHttpClient.java

private DefaultHttpClient createHttpClient(String userName, String password, int timeout) {
    BasicHttpParams params = new BasicHttpParams();
    int timeoutMilliSeconds = timeout * 1000;
    HttpConnectionParams.setConnectionTimeout(params, timeoutMilliSeconds);
    HttpConnectionParams.setSoTimeout(params, timeoutMilliSeconds);
    DefaultHttpClient client = new DefaultHttpClient(params);

    if (userName != null && !"".equals(userName)) {
        client.getCredentialsProvider().setCredentials(new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT),
                new UsernamePasswordCredentials(userName, password));
        localContext = new BasicHttpContext();

        // Generate BASIC scheme object and stick it to the local execution context
        BasicScheme basicAuth = new BasicScheme();
        localContext.setAttribute("preemptive-auth", basicAuth);

        // Add as the first request interceptor
        client.addRequestInterceptor(new PreemptiveAuth(), 0);
    }//from  w ww . jav a 2s  .  c om
    boolean requestSentRetryEnabled = Boolean.parseBoolean(System.getProperty("requestSentRetryEnabled"));
    if (requestSentRetryEnabled) {
        client.setHttpRequestRetryHandler(new DefaultHttpRequestRetryHandler(3, requestSentRetryEnabled));
    }
    // set the following user agent with each request
    String userAgent = "ArtifactoryBuildClient/" + CLIENT_VERSION;
    HttpProtocolParams.setUserAgent(client.getParams(), userAgent);
    return client;
}

From source file:com.suse.studio.api.lib.HttpClient.java

private DefaultHttpClient getHttpClient(final String userName, final String apiKey) {
    HttpRequestInterceptor preemptiveAuth = new HttpRequestInterceptor() {
        public void process(final HttpRequest request, final HttpContext context)
                throws HttpException, IOException {
            AuthState authState = (AuthState) context.getAttribute(ClientContext.TARGET_AUTH_STATE);
            if (authState.getAuthScheme() == null) {
                authState.setAuthScheme(new BasicScheme());
                authState.setCredentials(new UsernamePasswordCredentials(userName, apiKey));
            }/*from  w  w w.  j  av  a2 s  . c om*/
        }
    };
    DefaultHttpClient client = new DefaultHttpClient();
    client.addRequestInterceptor(preemptiveAuth, 0);
    return client;
}

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 va2 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();
    }
}