Example usage for org.apache.http.client AuthCache put

List of usage examples for org.apache.http.client AuthCache put

Introduction

In this page you can find the example usage for org.apache.http.client AuthCache put.

Prototype

void put(HttpHost host, AuthScheme authScheme);

Source Link

Usage

From source file:com.mirth.connect.connectors.http.HttpDispatcher.java

private void processDigestChallenge(AuthCache authCache, HttpHost target, Credentials credentials,
        HttpRequest request, HttpContext context) throws AuthenticationException {
    Header authHeader = request.getFirstHeader("Authorization");
    /*/*from  w w  w  .j  a v  a  2  s . co m*/
     * Since we're going to be replacing the header, we remove it here. If the header is invalid
     * or the challenge fails, we still want to remove the header, because otherwise it will
     * interfere with reactive authentication.
     */
    request.removeHeaders("Authorization");

    if (authHeader != null) {
        String authValue = authHeader.getValue();

        // The Authorization header value will be in the form: Digest param1="value1", param2="value2"
        if (StringUtils.startsWithIgnoreCase(authValue, AuthSchemes.DIGEST)) {
            DigestScheme digestScheme = new DigestScheme();

            // Get the actual parameters by stripping off the "Digest"
            authValue = StringUtils.removeStartIgnoreCase(authValue, AuthSchemes.DIGEST).trim();
            Matcher matcher = AUTH_HEADER_PATTERN.matcher(authValue);

            while (matcher.find()) {
                // We found a param="value" group
                String group = matcher.group();
                int index = group.indexOf('=');
                String name = group.substring(0, index).trim();
                String value = group.substring(index + 1).trim();

                // Strip off any quotes in the value
                if (value.startsWith("\"")) {
                    value = value.substring(1);
                }
                if (value.endsWith("\"")) {
                    value = value.substring(0, value.length() - 1);
                }

                logger.debug("Overriding Digest Parameter: " + name + "=\"" + value + "\"");
                digestScheme.overrideParamter(name, value);
            }

            // Since this is preemptive, we need to actually process the challenge beforehand
            request.addHeader(digestScheme.authenticate(credentials, request, context));
            authCache.put(target, digestScheme);
        }
    }
}

From source file:org.apache.hadoop.gateway.GatewayFuncTestDriver.java

public String oozieSubmitJob(String user, String password, String request, int status)
        throws IOException, URISyntaxException {
    getMock("OOZIE").expect().method("POST").pathInfo("/v1/jobs").respond().status(HttpStatus.SC_CREATED)
            .content(getResourceBytes("oozie-jobs-submit-response.json")).contentType("application/json");
    //System.out.println( "REQUEST LENGTH = " + request.length() );

    URL url = new URL(getUrl("OOZIE") + "/v1/jobs?action=start" + (isUseGateway() ? "" : "&user.name=" + user));
    HttpHost targetHost = new HttpHost(url.getHost(), url.getPort(), url.getProtocol());
    DefaultHttpClient client = new DefaultHttpClient();
    client.getCredentialsProvider().setCredentials(new AuthScope(targetHost),
            new UsernamePasswordCredentials(user, password));

    // 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
    BasicHttpContext localContext = new BasicHttpContext();
    localContext.setAttribute(ClientContext.AUTH_CACHE, authCache);

    HttpPost post = new HttpPost(url.toURI());
    //    post.getParams().setParameter( "action", "start" );
    StringEntity entity = new StringEntity(request, ContentType.create("application/xml", "UTF-8"));
    post.setEntity(entity);//from  w  w  w. j  av a2  s .  c  o m
    post.setHeader("X-XSRF-Header", "ksdjfhdsjkfhds");
    HttpResponse response = client.execute(targetHost, post, localContext);
    assertThat(response.getStatusLine().getStatusCode(), is(status));
    String json = EntityUtils.toString(response.getEntity());

    //    String json = given()
    //        .log().all()
    //        .auth().preemptive().basic( user, password )
    //        .queryParam( "action", "start" )
    //        .contentType( "application/xml;charset=UTF-8" )
    //        .content( request )
    //        .expect()
    //        .log().all()
    //        .statusCode( status )
    //        .when().post( getUrl( "OOZIE" ) + "/v1/jobs" + ( isUseGateway() ? "" : "?user.name=" + user ) ).asString();
    //System.out.println( "JSON=" + json );
    String id = from(json).getString("id");
    return id;
}

From source file:org.apache.hadoop.gateway.GatewayFuncTestDriver.java

public String oozieQueryJobStatus(String user, String password, String id, int status) throws Exception {
    getMock("OOZIE").expect().method("GET").pathInfo("/v1/job/" + id).respond().status(HttpStatus.SC_OK)
            .content(getResourceBytes("oozie-job-show-info.json")).contentType("application/json");

    //NOTE:  For some reason REST-assured doesn't like this and ends up failing with Content-Length issues.
    URL url = new URL(getUrl("OOZIE") + "/v1/job/" + id + (isUseGateway() ? "" : "?user.name=" + user));
    HttpHost targetHost = new HttpHost(url.getHost(), url.getPort(), url.getProtocol());
    DefaultHttpClient client = new DefaultHttpClient();
    client.getCredentialsProvider().setCredentials(new AuthScope(targetHost),
            new UsernamePasswordCredentials(user, password));

    // 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
    BasicHttpContext localContext = new BasicHttpContext();
    localContext.setAttribute(ClientContext.AUTH_CACHE, authCache);

    HttpGet request = new HttpGet(url.toURI());
    request.setHeader("X-XSRF-Header", "ksdhfjkhdsjkf");
    HttpResponse response = client.execute(targetHost, request, localContext);
    assertThat(response.getStatusLine().getStatusCode(), is(status));
    String json = EntityUtils.toString(response.getEntity());
    String jobStatus = from(json).getString("status");
    return jobStatus;
}

From source file:org.apache.http.client.protocol.ResponseAuthCache.java

private void cache(final AuthCache authCache, final HttpHost host, final AuthScheme authScheme) {
    if (this.log.isDebugEnabled()) {
        this.log.debug("Caching '" + authScheme.getSchemeName() + "' auth scheme for " + host);
    }//w  w w .  j a v a 2s.  c  o  m
    authCache.put(host, authScheme);
}

From source file:org.apache.http.impl.client.AuthenticationStrategyAdaptor.java

public void authSucceeded(final HttpHost authhost, final AuthScheme authScheme, final HttpContext context) {
    AuthCache authCache = (AuthCache) context.getAttribute(ClientContext.AUTH_CACHE);
    if (isCachable(authScheme)) {
        if (authCache == null) {
            authCache = new BasicAuthCache();
            context.setAttribute(ClientContext.AUTH_CACHE, authCache);
        }//from   w  ww .  ja  va2s  . c  o m
        if (this.log.isDebugEnabled()) {
            this.log.debug("Caching '" + authScheme.getSchemeName() + "' auth scheme for " + authhost);
        }
        authCache.put(authhost, authScheme);
    }
}

From source file:org.apache.http.impl.client.AuthenticationStrategyImpl.java

public void authSucceeded(final HttpHost authhost, final AuthScheme authScheme, final HttpContext context) {
    Args.notNull(authhost, "Host");
    Args.notNull(authScheme, "Auth scheme");
    Args.notNull(context, "HTTP context");

    final HttpClientContext clientContext = HttpClientContext.adapt(context);

    if (isCachable(authScheme)) {
        AuthCache authCache = clientContext.getAuthCache();
        if (authCache == null) {
            authCache = new BasicAuthCache();
            clientContext.setAuthCache(authCache);
        }/*from   ww  w. ja v  a2  s .  c o m*/
        if (this.log.isDebugEnabled()) {
            this.log.debug("Caching '" + authScheme.getSchemeName() + "' auth scheme for " + authhost);
        }
        authCache.put(authhost, authScheme);
    }
}

From source file:org.apache.tomcat.maven.common.deployer.TomcatManager.java

/**
 * Creates a Tomcat manager wrapper for the specified URL, username, password and URL encoding.
 *
 * @param url      the full URL of the Tomcat manager instance to use
 * @param username the username to use when authenticating with Tomcat manager
 * @param password the password to use when authenticating with Tomcat manager
 * @param charset  the URL encoding charset to use when communicating with Tomcat manager
 * @param verbose  if the build is in verbose mode (quiet mode otherwise)
 * @since 2.2/* www .j  av  a 2s  .  c  o  m*/
 */
public TomcatManager(URL url, String username, String password, String charset, boolean verbose) {
    this.url = url;
    this.username = username;
    this.password = password;
    this.charset = charset;
    this.verbose = verbose;

    PoolingClientConnectionManager poolingClientConnectionManager = new PoolingClientConnectionManager();
    poolingClientConnectionManager.setMaxTotal(5);
    this.httpClient = new DefaultHttpClient(poolingClientConnectionManager);
    if (StringUtils.isNotEmpty(username)) {
        Credentials creds = new UsernamePasswordCredentials(username, password);

        String host = url.getHost();
        int port = url.getPort() > -1 ? url.getPort() : AuthScope.ANY_PORT;

        httpClient.getCredentialsProvider().setCredentials(new AuthScope(host, port), creds);

        AuthCache authCache = new BasicAuthCache();
        BasicScheme basicAuth = new BasicScheme();
        HttpHost targetHost = new HttpHost(url.getHost(), url.getPort(), url.getProtocol());
        authCache.put(targetHost, basicAuth);

        localContext = new BasicHttpContext();
        localContext.setAttribute(ClientContext.AUTH_CACHE, authCache);
    }
}

From source file:org.fcrepo.client.utils.HttpHelper.java

/**
 * Create an HTTP helper with a pre-configured HttpClient instance.
 * @param repositoryURL Fedora base URL.
 * @param httpClient Pre-configured HttpClient instance.
 * @param readOnly If true, throw an exception when an update is attempted.
**///w w w .  ja  va 2 s.c o m
public HttpHelper(final String repositoryURL, final HttpClient httpClient, final boolean readOnly) {
    this.repositoryURL = repositoryURL;
    this.httpClient = httpClient;
    this.readOnly = readOnly;

    // Use pre-emptive Auth whether the repository is actually protected or not.
    final URI uri = URI.create(repositoryURL);
    final HttpHost target = new HttpHost(uri.getHost(), uri.getPort(), uri.getScheme());

    final AuthCache authCache = new BasicAuthCache();
    final BasicScheme basicAuth = new BasicScheme();
    authCache.put(target, basicAuth);

    // Add AuthCache to the execution context
    final HttpClientContext localContext = HttpClientContext.create();
    localContext.setAuthCache(authCache);

    this.httpContext = localContext;
}

From source file:org.hyperic.hq.hqapi1.HQConnection.java

private <T> T runMethod(HttpRequestBase method, String uri, ResponseHandler<T> responseHandler)
        throws IOException {
    String protocol = _isSecure ? "https" : "http";
    ServiceError error;/*from   w w w .j ava 2  s  .  c  o  m*/
    URL url = new URL(protocol, _host, _port, uri);

    try {
        method.setURI(url.toURI());
    } catch (URISyntaxException e) {
        throw new IllegalArgumentException("The syntax of request url [" + uri + "] is invalid", e);
    }

    _log.debug("Setting URI: " + url.toString());

    DefaultHttpClient client = new DefaultHttpClient();

    if (_isSecure) {
        // To allow for self signed certificates
        configureSSL(client);
    }

    // Validate user & password inputs
    if (_user == null || _user.length() == 0) {
        error = new ServiceError();
        error.setErrorCode("LoginFailure");
        error.setReasonText("User name cannot be null or empty");

        return responseHandler.getErrorResponse(error);
    }

    if (_password == null || _password.length() == 0) {
        error = new ServiceError();
        error.setErrorCode("LoginFailure");
        error.setReasonText("Password cannot be null or empty");

        return responseHandler.getErrorResponse(error);
    }

    // Set Basic auth creds
    UsernamePasswordCredentials defaultcreds = new UsernamePasswordCredentials(_user, _password);

    client.getCredentialsProvider().setCredentials(AuthScope.ANY, defaultcreds);

    // Preemptive authentication
    AuthCache authCache = new BasicAuthCache();
    BasicScheme basicAuth = new BasicScheme();
    HttpHost host = new HttpHost(_host, _port, protocol);

    authCache.put(host, basicAuth);

    BasicHttpContext localContext = new BasicHttpContext();
    localContext.setAttribute(ClientContext.AUTH_CACHE, authCache);

    method.getParams().setParameter(ClientPNames.HANDLE_AUTHENTICATION, true);

    // Disable re-tries
    client.setHttpRequestRetryHandler(new DefaultHttpRequestRetryHandler(0, true));

    HttpResponse response = client.execute(method, localContext);

    return responseHandler.handleResponse(response);
}

From source file:org.hyperic.hq.plugin.rabbitmq.core.HypericRabbitAdmin.java

public HypericRabbitAdmin(Properties props) throws PluginException {
    int port = Integer.parseInt(props.getProperty(DetectorConstants.PORT));
    String addr = props.getProperty(DetectorConstants.ADDR);
    boolean https = "true".equals(props.getProperty(DetectorConstants.HTTPS));
    this.user = props.getProperty(DetectorConstants.USERNAME);
    this.pass = props.getProperty(DetectorConstants.PASSWORD);

    targetHost = new HttpHost(addr, port, https ? "https" : "http");
    AgentKeystoreConfig config = new AgentKeystoreConfig();
    client = new HQHttpClient(config, new HttpConfig(5000, 5000, null, 0), config.isAcceptUnverifiedCert());
    client.getCredentialsProvider().setCredentials(
            new AuthScope(targetHost.getHostName(), targetHost.getPort(), "Management: Web UI"),
            new UsernamePasswordCredentials(user, pass));
    List authPrefs = new ArrayList(1);
    authPrefs.add("Management: Web UI");

    AuthCache authCache = new BasicAuthCache();
    BasicScheme basicAuth = new BasicScheme();
    authCache.put(targetHost, basicAuth);

    localcontext = new BasicHttpContext();
    localcontext.setAttribute(ClientContext.AUTH_CACHE, authCache);
}