Example usage for org.apache.commons.httpclient.auth BasicScheme BasicScheme

List of usage examples for org.apache.commons.httpclient.auth BasicScheme BasicScheme

Introduction

In this page you can find the example usage for org.apache.commons.httpclient.auth BasicScheme BasicScheme.

Prototype

public BasicScheme() 

Source Link

Usage

From source file:com.mycompany.projecta.Test.java

public void Auth() throws Exception {

    // Credentials
    String username = "fernandoadp";
    String password = "ADP.2017";

    // Jenkins url
    String jenkinsUrl = "http://localhost:8080";

    // Build name
    String jobName = "ServiceA";

    // Build token
    String buildToken = "build";

    // Create your httpclient
    DefaultHttpClient client = new DefaultHttpClient();

    // Then provide the right credentials *******************
    client.getCredentialsProvider().setCredentials(new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT),
            new org.apache.http.auth.UsernamePasswordCredentials(username, password));
    //client.getCredentialsProvider().setCredentials(new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT), (Credentials) new UsernamePasswordCredentials(username, password));

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

    // Add as the first (because of the zero) request interceptor
    // It will first intercept the request and preemptively initialize the authentication scheme if there is not
    client.addRequestInterceptor(new PreemptiveAuth(), 0);

    // You get request that will start the build
    String getUrl = jenkinsUrl + "/job/" + jobName + "/build?token=" + buildToken;
    HttpGet get = new HttpGet(getUrl);

    try {/*from w ww  .  j a  va2 s .  c  o  m*/
        // Execute your request with the given context
        HttpResponse response = client.execute(get, context);
        HttpEntity entity = response.getEntity();
        EntityUtils.consume(entity);
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}

From source file:io.fabric8.quickstarts.fabric.rest.secure.CrmSecureTest.java

@Before
public void beforeTest() {
    // Now we need to use the basic authentication to send the request
    httpClient = new HttpClient();
    httpClient.getState().setCredentials(AuthScope.ANY, new UsernamePasswordCredentials("admin", "admin"));
    // Use basic authentication
    scheme = new BasicScheme();

}

From source file:com.gargoylesoftware.htmlunit.DefaultCredentialsProviderTest.java

/**
 * Test that successive calls to {@link DefaultCredentialsProvider#addCredentials(String, String)}
 * overwrite values previously set.//w w w . j a  va  2 s . c om
 * @throws Exception if the test fails
 */
@Test
public void overwrite() throws Exception {
    final DefaultCredentialsProvider provider = new DefaultCredentialsProvider();
    provider.addCredentials("username", "password");

    UsernamePasswordCredentials credentials = (UsernamePasswordCredentials) provider
            .getCredentials(new BasicScheme(), "host", 80, false);
    assertEquals("username", credentials.getUserName());
    assertEquals("password", credentials.getPassword());

    provider.addCredentials("username", "new password");
    credentials = (UsernamePasswordCredentials) provider.getCredentials(new BasicScheme(), "host", 80, false);
    assertEquals("username", credentials.getUserName());
    assertEquals("new password", credentials.getPassword());

    provider.addCredentials("new username", "other password");
    credentials = (UsernamePasswordCredentials) provider.getCredentials(new BasicScheme(), "host", 80, false);
    assertEquals("new username", credentials.getUserName());
    assertEquals("other password", credentials.getPassword());
}

From source file:com.cyberway.issue.crawler.fetcher.FetchHTTP.java

/**
 * @param method Method that got a 401./*from ww  w . j a v a2 s.  c  o m*/
 * @param curi CrawlURI that got a 401.
 * @return Returns first wholesome authscheme found else null.
 */
protected AuthScheme getAuthScheme(final HttpMethod method, final CrawlURI curi) {
    Header[] headers = method.getResponseHeaders("WWW-Authenticate");
    if (headers == null || headers.length <= 0) {
        logger.info("We got a 401 but no WWW-Authenticate challenge: " + curi.toString());
        return null;
    }

    Map authschemes = null;
    try {
        authschemes = AuthChallengeParser.parseChallenges(headers);
    } catch (MalformedChallengeException e) {
        logger.info("Failed challenge parse: " + e.getMessage());
    }
    if (authschemes == null || authschemes.size() <= 0) {
        logger.info("We got a 401 and WWW-Authenticate challenge" + " but failed parse of the header "
                + curi.toString());
        return null;
    }

    AuthScheme result = null;
    // Use the first auth found.
    for (Iterator i = authschemes.keySet().iterator(); result == null && i.hasNext();) {
        String key = (String) i.next();
        String challenge = (String) authschemes.get(key);
        if (key == null || key.length() <= 0 || challenge == null || challenge.length() <= 0) {
            logger.warning("Empty scheme: " + curi.toString() + ": " + headers);
        }
        AuthScheme authscheme = null;
        if (key.equals("basic")) {
            authscheme = new BasicScheme();
        } else if (key.equals("digest")) {
            authscheme = new DigestScheme();
        } else {
            logger.info("Unsupported scheme: " + key);
            continue;
        }

        try {
            authscheme.processChallenge(challenge);
        } catch (MalformedChallengeException e) {
            logger.info(e.getMessage() + " " + curi + " " + headers);
            continue;
        }
        if (authscheme.isConnectionBased()) {
            logger.info("Connection based " + authscheme);
            continue;
        }

        if (authscheme.getRealm() == null || authscheme.getRealm().length() <= 0) {
            logger.info("Empty realm " + authscheme + " for " + curi);
            continue;
        }
        result = authscheme;
    }

    return result;
}

From source file:org.archive.crawler.fetcher.OptimizeFetchHTTP.java

/**
 * @param method Method that got a 401.//from w ww  . java  2s  . c  o  m
 * @param curi CrawlURI that got a 401.
 * @return Returns first wholesome authscheme found else null.
 */
protected AuthScheme getAuthScheme(final HttpMethod method, final CrawlURI curi) {
    Header[] headers = method.getResponseHeaders("WWW-Authenticate");
    if (headers == null || headers.length <= 0) {
        logger.info("We got a 401 but no WWW-Authenticate challenge: " + curi.toString());
        return null;
    }

    Map authschemes = null;
    try {
        authschemes = AuthChallengeParser.parseChallenges(headers);
    } catch (MalformedChallengeException e) {
        logger.info("Failed challenge parse: " + e.getMessage());
    }
    if (authschemes == null || authschemes.size() <= 0) {
        logger.info("We got a 401 and WWW-Authenticate challenge" + " but failed parse of the header "
                + curi.toString());
        return null;
    }

    AuthScheme result = null;
    // Use the first auth found.
    for (Iterator i = authschemes.keySet().iterator(); result == null && i.hasNext();) {
        String key = (String) i.next();
        String challenge = (String) authschemes.get(key);
        if (key == null || key.length() <= 0 || challenge == null || challenge.length() <= 0) {
            logger.warn("Empty scheme: " + curi.toString() + ": " + headers);
        }
        AuthScheme authscheme = null;
        if (key.equals("basic")) {
            authscheme = new BasicScheme();
        } else if (key.equals("digest")) {
            authscheme = new DigestScheme();
        } else {
            logger.info("Unsupported scheme: " + key);
            continue;
        }

        try {
            authscheme.processChallenge(challenge);
        } catch (MalformedChallengeException e) {
            logger.info(e.getMessage() + " " + curi + " " + headers);
            continue;
        }
        if (authscheme.isConnectionBased()) {
            logger.info("Connection based " + authscheme);
            continue;
        }

        if (authscheme.getRealm() == null || authscheme.getRealm().length() <= 0) {
            logger.info("Empty realm " + authscheme + " for " + curi);
            continue;
        }
        result = authscheme;
    }

    return result;
}

From source file:org.jboss.fuse.examples.cxf.jaxrs.security.client.Client.java

public static void main(String args[]) throws Exception {
    // Now we need to use the basic authentication to send the request
    HttpClient httpClient = new HttpClient();
    httpClient.getState().setCredentials(AuthScope.ANY, new UsernamePasswordCredentials("admin", "admin"));
    // Use basic authentication
    AuthScheme scheme = new BasicScheme();

    /**//  www . j  av  a  2  s. c  o  m
     * HTTP GET http://localhost:8181/cxf/securecrm/customerservice/customers/123
     * returns the XML document representing customer 123
     *
     * On the server side, it matches the CustomerService's getCustomer() method
     */
    System.out.println("Sent HTTP GET request to query customer info with basic authentication info.");
    GetMethod get = new GetMethod("http://localhost:8181/cxf/securecrm/customerservice/customers/123");
    get.getHostAuthState().setAuthScheme(scheme);
    try {
        httpClient.executeMethod(get);
        System.out.println(get.getResponseBodyAsString());
    } finally {
        get.releaseConnection();
    }

    /**
     * HTTP GET http://localhost:8181/cxf/securecrm/customerservice/customers/123
     * without passing along authentication credentials - this will result in a security exception in the response.
     */
    System.out.println("\n");
    System.out.println("Sent HTTP GET request to query customer info without basic authentication info.");
    get = new GetMethod("http://localhost:8181/cxf/securecrm/customerservice/customers/123");
    try {
        httpClient.executeMethod(get);
        // we should get the security exception here
        System.out.println(get.getResponseBodyAsString());
    } finally {
        get.releaseConnection();
    }

    /**
     * HTTP GET http://localhost:8181/cxf/securecrm/customerservice/orders/223/products/323
     * returns the XML document representing product 323 in order 223
     *
     * On the server side, it matches the Order's getProduct() method
     */
    System.out.println("\n");
    System.out.println("Sent HTTP GET request to query sub resource product info");
    get = new GetMethod("http://localhost:8181/cxf/securecrm/customerservice/orders/223/products/323");
    get.getHostAuthState().setAuthScheme(scheme);
    try {
        httpClient.executeMethod(get);
        System.out.println(get.getResponseBodyAsString());
    } finally {
        get.releaseConnection();
    }

    /**
     * HTTP PUT http://localhost:8181/cxf/securecrm/customerservice/customers is used to upload the contents of
     * the update_customer.xml file to update the customer information for customer 123.
     *
     * On the server side, it matches the CustomerService's updateCustomer() method
     */
    System.out.println("\n");
    System.out.println("Sent HTTP PUT request to update customer info");

    String inputFile = Client.class.getResource("update_customer.xml").getFile();
    File input = new File(inputFile);
    PutMethod put = new PutMethod("http://localhost:8181/cxf/securecrm/customerservice/customers");
    put.getHostAuthState().setAuthScheme(scheme);
    RequestEntity entity = new FileRequestEntity(input, "text/xml; charset=ISO-8859-1");
    put.setRequestEntity(entity);

    try {
        int result = httpClient.executeMethod(put);
        System.out.println("Response status code: " + result);
        System.out.println("Response body: ");
        System.out.println(put.getResponseBodyAsString());
    } finally {
        // Release current connection to the connection pool once you are
        // done
        put.releaseConnection();
    }

    /**
     * HTTP POST http://localhost:8181/cxf/securecrm/customerservice/customers is used to upload the contents of
     * the add_customer.xml file to add a new customer to the system.
     *
     * On the server side, it matches the CustomerService's addCustomer() method
     */
    System.out.println("\n");
    System.out.println("Sent HTTP POST request to add customer");
    inputFile = Client.class.getResource("add_customer.xml").getFile();
    input = new File(inputFile);
    PostMethod post = new PostMethod("http://localhost:8181/cxf/securecrm/customerservice/customers");
    post.getHostAuthState().setAuthScheme(scheme);
    post.addRequestHeader("Accept", "text/xml");
    entity = new FileRequestEntity(input, "text/xml; charset=ISO-8859-1");
    post.setRequestEntity(entity);

    try {
        int result = httpClient.executeMethod(post);
        System.out.println("Response status code: " + result);
        System.out.println("Response body: ");
        System.out.println(post.getResponseBodyAsString());
    } finally {
        // Release current connection to the connection pool once you are
        // done
        post.releaseConnection();
    }

    System.out.println("\n");
    System.exit(0);
}

From source file:org.review_board.ereviewboard.core.client.ReviewboardHttpClient.java

public String login(String username, String password, IProgressMonitor monitor) throws ReviewboardException {

    GetMethod loginRequest = new GetMethod(location.getUrl() + "/api/info/");
    Credentials credentials = new UsernamePasswordCredentials(username, password);

    monitor = Policy.monitorFor(monitor);

    String foundSessionCookie = null;

    try {//w  ww.  j  av a 2 s  .  c  o m
        monitor.beginTask("Logging in", IProgressMonitor.UNKNOWN);

        // TODO: this will probably affect existing requests, might have ill side-effects
        httpClient.getState().clearCookies();

        // perform authentication
        String authHeader = new BasicScheme().authenticate(credentials, loginRequest);
        loginRequest.addRequestHeader("Authorization", authHeader);

        // execute and validate call
        int requestStatus = executeRequest(loginRequest, monitor);

        switch (requestStatus) {

        case HttpStatus.SC_OK:
            break;
        case HttpStatus.SC_UNAUTHORIZED:
            throw new ReviewboardException("Authentication failed, please check your username and password");
        default:
            throw new ReviewboardException("Request returned unacceptable status code " + requestStatus);
        }

        // look for session cookie
        for (Cookie cookie : httpClient.getState().getCookies())
            if (cookie.getName().equals("rbsessionid"))
                foundSessionCookie = cookie.getValue();

        if (foundSessionCookie == null)
            throw new ReviewboardException("Did not find session cookie in response");

        return foundSessionCookie;

    } catch (AuthenticationException e) {
        throw new ReviewboardException(e.getMessage(), e);
    } finally {
        loginRequest.releaseConnection();
        monitor.done();
    }
}