Search in sources :

Example 56 with HttpClientContext

use of org.apache.http.client.protocol.HttpClientContext in project zm-mailbox by Zimbra.

the class TestCookieReuse method testAutoEndSession.

/**
 * Verify that we canNOT RE-use the cookie for REST session if the session is valid
 * @throws HttpException
 */
@Test
public void testAutoEndSession() throws ServiceException, IOException, HttpException {
    // establish legitimate connection
    TestUtil.setAccountAttr(USER_NAME, Provisioning.A_zimbraForceClearCookies, "TRUE");
    ZMailbox mbox = TestUtil.getZMailbox(USER_NAME);
    URI uri = mbox.getRestURI("Inbox?fmt=rss");
    HttpClientContext context = HttpClientContext.create();
    HttpClient alice = mbox.getHttpClient(uri);
    // create evesdropper's connection
    HttpClientBuilder eve = ZimbraHttpConnectionManager.getInternalHttpConnMgr().newHttpClient();
    List<Cookie> cookies = context.getCookieStore().getCookies();
    BasicCookieStore cookieStore = new BasicCookieStore();
    for (Cookie cookie : cookies) {
        BasicClientCookie basicCookie = new BasicClientCookie(cookie.getName(), cookie.getValue());
        basicCookie.setDomain(uri.getHost());
        basicCookie.setPath("/");
        basicCookie.setSecure(false);
        cookieStore.addCookie(cookie);
    }
    eve.setDefaultCookieStore(cookieStore);
    Account a = TestUtil.getAccount(USER_NAME);
    a.setForceClearCookies(true);
    EndSessionRequest esr = new EndSessionRequest();
    mbox.invokeJaxb(esr);
    HttpGet get = new HttpGet(uri.toString());
    HttpResponse response = HttpClientUtil.executeMethod(eve.build(), get, context);
    int statusCode = response.getStatusLine().getStatusCode();
    Assert.assertEquals("This request should not succeed. Getting status code " + statusCode, HttpStatus.SC_UNAUTHORIZED, statusCode);
}
Also used : Cookie(org.apache.http.cookie.Cookie) BasicClientCookie(org.apache.http.impl.cookie.BasicClientCookie) Account(com.zimbra.cs.account.Account) HttpGet(org.apache.http.client.methods.HttpGet) HttpResponse(org.apache.http.HttpResponse) HttpClientContext(org.apache.http.client.protocol.HttpClientContext) HttpClientBuilder(org.apache.http.impl.client.HttpClientBuilder) BasicClientCookie(org.apache.http.impl.cookie.BasicClientCookie) URI(java.net.URI) BasicCookieStore(org.apache.http.impl.client.BasicCookieStore) ZMailbox(com.zimbra.client.ZMailbox) HttpClient(org.apache.http.client.HttpClient) EndSessionRequest(com.zimbra.soap.account.message.EndSessionRequest) Test(org.junit.Test)

Example 57 with HttpClientContext

use of org.apache.http.client.protocol.HttpClientContext in project zm-mailbox by Zimbra.

the class TestCookieReuse method testForceEndSession.

/**
 * Verify that we canNOT RE-use the cookie taken from a legitimate HTTP session for a REST request
 * after ending the original session
 * @throws HttpException
 */
@Test
public void testForceEndSession() throws ServiceException, IOException, HttpException {
    // establish legitimate connection
    TestUtil.setAccountAttr(USER_NAME, Provisioning.A_zimbraForceClearCookies, "FALSE");
    ZMailbox mbox = TestUtil.getZMailbox(USER_NAME);
    URI uri = mbox.getRestURI("Inbox?fmt=rss");
    HttpClient alice = mbox.getHttpClient(uri);
    HttpClientContext context = HttpClientContext.create();
    // create evesdropper's connection
    HttpClientBuilder eve = ZimbraHttpConnectionManager.getInternalHttpConnMgr().newHttpClient();
    List<Cookie> cookies = context.getCookieStore().getCookies();
    BasicCookieStore cookieStore = new BasicCookieStore();
    for (Cookie cookie : cookies) {
        BasicClientCookie basicCookie = new BasicClientCookie(cookie.getName(), cookie.getValue());
        basicCookie.setDomain(uri.getHost());
        basicCookie.setPath("/");
        basicCookie.setSecure(false);
        cookieStore.addCookie(cookie);
    }
    eve.setDefaultCookieStore(cookieStore);
    Account a = TestUtil.getAccount(USER_NAME);
    a.setForceClearCookies(false);
    EndSessionRequest esr = new EndSessionRequest();
    esr.setLogOff(true);
    mbox.invokeJaxb(esr);
    HttpGet get = new HttpGet(uri.toString());
    HttpResponse response = HttpClientUtil.executeMethod(eve.build(), get);
    int statusCode = response.getStatusLine().getStatusCode();
    Assert.assertEquals("This request should not succeed. Getting status code " + statusCode, HttpStatus.SC_UNAUTHORIZED, statusCode);
}
Also used : Cookie(org.apache.http.cookie.Cookie) BasicClientCookie(org.apache.http.impl.cookie.BasicClientCookie) Account(com.zimbra.cs.account.Account) HttpGet(org.apache.http.client.methods.HttpGet) HttpResponse(org.apache.http.HttpResponse) HttpClientContext(org.apache.http.client.protocol.HttpClientContext) HttpClientBuilder(org.apache.http.impl.client.HttpClientBuilder) BasicClientCookie(org.apache.http.impl.cookie.BasicClientCookie) URI(java.net.URI) BasicCookieStore(org.apache.http.impl.client.BasicCookieStore) ZMailbox(com.zimbra.client.ZMailbox) HttpClient(org.apache.http.client.HttpClient) EndSessionRequest(com.zimbra.soap.account.message.EndSessionRequest) Test(org.junit.Test)

Example 58 with HttpClientContext

use of org.apache.http.client.protocol.HttpClientContext in project project-build-plugin by axonivy.

the class HttpDeployer method getRequestContext.

private HttpClientContext getRequestContext(String url) throws URISyntaxException, MojoExecutionException {
    String username = "admin";
    String password = "admin";
    if (server != null) {
        username = server.getUsername();
        try {
            password = secDispatcher.decrypt(server.getPassword());
        } catch (SecDispatcherException ex) {
            throw new MojoExecutionException("Could not decrypt maven password", ex);
        }
    }
    HttpHost httpHost = URIUtils.extractHost(new URI(url));
    CredentialsProvider credsProvider = new BasicCredentialsProvider();
    credsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(username, password));
    AuthCache authCache = new BasicAuthCache();
    authCache.put(httpHost, new BasicScheme());
    HttpClientContext context = HttpClientContext.create();
    context.setCredentialsProvider(credsProvider);
    context.setAuthCache(authCache);
    return context;
}
Also used : BasicScheme(org.apache.http.impl.auth.BasicScheme) BasicCredentialsProvider(org.apache.http.impl.client.BasicCredentialsProvider) MojoExecutionException(org.apache.maven.plugin.MojoExecutionException) HttpHost(org.apache.http.HttpHost) AuthCache(org.apache.http.client.AuthCache) BasicAuthCache(org.apache.http.impl.client.BasicAuthCache) HttpClientContext(org.apache.http.client.protocol.HttpClientContext) BasicCredentialsProvider(org.apache.http.impl.client.BasicCredentialsProvider) CredentialsProvider(org.apache.http.client.CredentialsProvider) BasicAuthCache(org.apache.http.impl.client.BasicAuthCache) SecDispatcherException(org.sonatype.plexus.components.sec.dispatcher.SecDispatcherException) URI(java.net.URI) UsernamePasswordCredentials(org.apache.http.auth.UsernamePasswordCredentials)

Example 59 with HttpClientContext

use of org.apache.http.client.protocol.HttpClientContext in project metron by apache.

the class RestFunctions method executeRequest.

/**
 * Perform the HttpClient request and handle the results.  A configurable list of status codes are accepted and the
 * response content (expected to be json) is parsed into a Map.  Values returned on errors and when response content
 * is also configurable.  The rest config "timeout" setting is imposed in this method and will abort the get request
 * if exceeded.
 *
 * @param restConfig
 * @param httpRequestBase
 * @return
 * @throws IOException
 */
protected static Object executeRequest(RestConfig restConfig, HttpRequestBase httpRequestBase) throws IOException {
    URI uri = httpRequestBase.getURI();
    HttpHost target = new HttpHost(uri.getHost(), uri.getPort(), uri.getScheme());
    Optional<HttpHost> proxy = getProxy(restConfig);
    HttpClientContext httpClientContext = getHttpClientContext(restConfig, target, proxy);
    httpRequestBase.setConfig(getRequestConfig(restConfig, proxy));
    // Schedule a command to abort the request if the timeout is exceeded
    ScheduledFuture scheduledFuture = scheduledExecutorService.schedule(httpRequestBase::abort, restConfig.getTimeout(), TimeUnit.MILLISECONDS);
    CloseableHttpResponse response;
    try {
        response = closeableHttpClient.execute(httpRequestBase, httpClientContext);
    } catch (Exception e) {
        // Report a timeout if the httpGet request was aborted.  Otherwise rethrow exception.
        if (httpRequestBase.isAborted()) {
            throw new IOException(String.format("Total Stellar REST request time to %s exceeded the configured timeout of %d ms.", httpRequestBase.getURI().toString(), restConfig.getTimeout()));
        } else {
            throw e;
        }
    }
    // Cancel the future if the request finished within the timeout
    if (!scheduledFuture.isDone()) {
        scheduledFuture.cancel(true);
    }
    int statusCode = response.getStatusLine().getStatusCode();
    LOG.debug("request = {}; response = {}", httpRequestBase, response);
    if (restConfig.getResponseCodesAllowed().contains(statusCode)) {
        HttpEntity httpEntity = response.getEntity();
        // Parse the response if present, return the empty value override if not
        Optional<Object> parsedResponse = parseResponse(restConfig, httpRequestBase, httpEntity);
        return parsedResponse.orElseGet(restConfig::getEmptyContentOverride);
    } else {
        throw new IOException(String.format("Stellar REST request to %s expected status code to be one of %s but " + "failed with http status code %d: %s", httpRequestBase.getURI().toString(), restConfig.getResponseCodesAllowed().toString(), statusCode, EntityUtils.toString(response.getEntity())));
    }
}
Also used : HttpEntity(org.apache.http.HttpEntity) HttpClientContext(org.apache.http.client.protocol.HttpClientContext) IOException(java.io.IOException) URI(java.net.URI) ScheduledFuture(java.util.concurrent.ScheduledFuture) URISyntaxException(java.net.URISyntaxException) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException) IOException(java.io.IOException) ParseException(org.apache.metron.stellar.dsl.ParseException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) HttpHost(org.apache.http.HttpHost)

Example 60 with HttpClientContext

use of org.apache.http.client.protocol.HttpClientContext in project metron by apache.

the class RestFunctions method getHttpClientContext.

/**
 * Builds the HttpClientContext object by setting the basic auth and/or proxy basic auth credentials when the
 * necessary rest config settings are configured.  Passwords are stored in HDFS.
 * @param restConfig
 * @param target
 * @param proxy
 * @return
 * @throws IOException
 */
protected static HttpClientContext getHttpClientContext(RestConfig restConfig, HttpHost target, Optional<HttpHost> proxy) throws IOException {
    HttpClientContext httpClientContext = HttpClientContext.create();
    boolean credentialsAdded = false;
    CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
    // Add the basic auth credentials if the rest config settings are present
    if (restConfig.getBasicAuthUser() != null && restConfig.getBasicAuthPasswordPath() != null) {
        String password = new String(readBytes(new Path(restConfig.getBasicAuthPasswordPath())), StandardCharsets.UTF_8);
        credentialsProvider.setCredentials(new AuthScope(target), new UsernamePasswordCredentials(restConfig.getBasicAuthUser(), password));
        credentialsAdded = true;
    }
    // Add the proxy basic auth credentials if the rest config settings are present
    if (proxy.isPresent() && restConfig.getProxyBasicAuthUser() != null && restConfig.getProxyBasicAuthPasswordPath() != null) {
        String password = new String(readBytes(new Path(restConfig.getProxyBasicAuthPasswordPath())), StandardCharsets.UTF_8);
        credentialsProvider.setCredentials(new AuthScope(proxy.get()), new UsernamePasswordCredentials(restConfig.getProxyBasicAuthUser(), password));
        credentialsAdded = true;
    }
    if (credentialsAdded) {
        httpClientContext.setCredentialsProvider(credentialsProvider);
    }
    return httpClientContext;
}
Also used : Path(org.apache.hadoop.fs.Path) BasicCredentialsProvider(org.apache.http.impl.client.BasicCredentialsProvider) AuthScope(org.apache.http.auth.AuthScope) HttpClientContext(org.apache.http.client.protocol.HttpClientContext) BasicCredentialsProvider(org.apache.http.impl.client.BasicCredentialsProvider) CredentialsProvider(org.apache.http.client.CredentialsProvider) UsernamePasswordCredentials(org.apache.http.auth.UsernamePasswordCredentials)

Aggregations

HttpClientContext (org.apache.http.client.protocol.HttpClientContext)160 HttpGet (org.apache.http.client.methods.HttpGet)56 CloseableHttpResponse (org.apache.http.client.methods.CloseableHttpResponse)54 IOException (java.io.IOException)48 HttpHost (org.apache.http.HttpHost)47 BasicCredentialsProvider (org.apache.http.impl.client.BasicCredentialsProvider)45 CloseableHttpClient (org.apache.http.impl.client.CloseableHttpClient)45 UsernamePasswordCredentials (org.apache.http.auth.UsernamePasswordCredentials)39 CredentialsProvider (org.apache.http.client.CredentialsProvider)39 URI (java.net.URI)32 HttpResponse (org.apache.http.HttpResponse)32 BasicScheme (org.apache.http.impl.auth.BasicScheme)32 BasicAuthCache (org.apache.http.impl.client.BasicAuthCache)32 AuthScope (org.apache.http.auth.AuthScope)31 AuthCache (org.apache.http.client.AuthCache)29 Test (org.junit.Test)29 HttpEntity (org.apache.http.HttpEntity)22 HttpClientBuilder (org.apache.http.impl.client.HttpClientBuilder)21 HttpClient (org.apache.http.client.HttpClient)18 RequestConfig (org.apache.http.client.config.RequestConfig)17