Example usage for org.apache.http.client.config CookieSpecs STANDARD

List of usage examples for org.apache.http.client.config CookieSpecs STANDARD

Introduction

In this page you can find the example usage for org.apache.http.client.config CookieSpecs STANDARD.

Prototype

String STANDARD

To view the source code for org.apache.http.client.config CookieSpecs STANDARD.

Click Source Link

Document

The RFC 2965 compliant policy (standard).

Usage

From source file:com.tremolosecurity.unison.proxy.auth.openidconnect.OpenIDConnectAuthMech.java

public void doGet(HttpServletRequest request, HttpServletResponse response, AuthStep as)
        throws IOException, ServletException {

    HttpSession session = ((HttpServletRequest) request).getSession();
    HashMap<String, Attribute> authParams = (HashMap<String, Attribute>) session
            .getAttribute(ProxyConstants.AUTH_MECH_PARAMS);
    ConfigManager cfg = (ConfigManager) request.getAttribute(ProxyConstants.TREMOLO_CFG_OBJ);

    MyVDConnection myvd = cfg.getMyVD();

    String bearerTokenName = authParams.get("bearerTokenName").getValues().get(0);
    String clientid = authParams.get("clientid").getValues().get(0);
    String secret = authParams.get("secretid").getValues().get(0);
    String idpURL = authParams.get("idpURL").getValues().get(0);
    String responseType = authParams.get("responseType").getValues().get(0);
    String scope = authParams.get("scope").getValues().get(0);
    boolean linkToDirectory = Boolean.parseBoolean(authParams.get("linkToDirectory").getValues().get(0));
    String noMatchOU = authParams.get("noMatchOU").getValues().get(0);
    String uidAttr = authParams.get("uidAttr").getValues().get(0);
    String lookupFilter = authParams.get("lookupFilter").getValues().get(0);
    String userLookupClassName = authParams.get("userLookupClassName").getValues().get(0);

    String defaultObjectClass = authParams.get("defaultObjectClass").getValues().get(0);

    boolean forceAuth = true;//authParams.get("forceAuthentication") != null ? authParams.get("forceAuthentication").getValues().get(0).equalsIgnoreCase("true") : false;

    UrlHolder holder = (UrlHolder) request.getAttribute(ProxyConstants.AUTOIDM_CFG);
    RequestHolder reqHolder = ((AuthController) session.getAttribute(ProxyConstants.AUTH_CTL)).getHolder();

    StringBuffer b = new StringBuffer();

    URL reqURL = new URL(request.getRequestURL().toString());

    b.append(reqURL.getProtocol()).append("://").append(reqURL.getHost());

    if (reqURL.getPort() != -1) {
        b.append(":").append(reqURL.getPort());
    }//w  ww .  j a  v  a  2 s .  c  o  m

    String urlChain = holder.getUrl().getAuthChain();
    AuthChainType act = holder.getConfig().getAuthChains().get(reqHolder.getAuthChainName());

    AuthMechType amt = act.getAuthMech().get(as.getId());

    String authMechName = amt.getName();

    b.append(holder.getConfig().getContextPath()).append(cfg.getAuthMechs().get(authMechName).getUri());

    String hd = authParams.get("hd").getValues().get(0);
    String loadTokenURL = authParams.get("loadTokenURL").getValues().get(0);

    if (request.getParameter("state") == null) {
        //initialize openidconnect

        String state = new BigInteger(130, new SecureRandom()).toString(32);
        request.getSession().setAttribute("UNISON_OPENIDCONNECT_STATE", state);

        StringBuffer redirToSend = new StringBuffer();
        redirToSend.append(idpURL).append("?client_id=").append(URLEncoder.encode(clientid, "UTF-8"))
                .append("&response_type=").append(URLEncoder.encode(responseType, "UTF-8")).append("&scope=")
                .append(URLEncoder.encode(scope, "UTF-8")).append("&redirect_uri=")
                .append(URLEncoder.encode(b.toString(), "UTF-8")).append("&state=")
                .append(URLEncoder.encode("security_token=", "UTF-8"))
                .append(URLEncoder.encode(state, "UTF-8"));

        if (forceAuth) {
            redirToSend.append("&max_age=0");
        }

        if (!hd.isEmpty()) {
            redirToSend.append("&hd=").append(hd);
        }

        response.sendRedirect(redirToSend.toString());

    } else {
        String stateFromURL = request.getParameter("state");
        stateFromURL = URLDecoder.decode(stateFromURL, "UTF-8");
        stateFromURL = stateFromURL.substring(stateFromURL.indexOf('=') + 1);

        String stateFromSession = (String) request.getSession().getAttribute("UNISON_OPENIDCONNECT_STATE");

        if (!stateFromSession.equalsIgnoreCase(stateFromURL)) {
            throw new ServletException("Invalid State");
        }

        HttpUriRequest post = null;

        try {
            post = RequestBuilder.post().setUri(new java.net.URI(loadTokenURL))
                    .addParameter("code", request.getParameter("code")).addParameter("client_id", clientid)
                    .addParameter("client_secret", secret).addParameter("redirect_uri", b.toString())
                    .addParameter("grant_type", "authorization_code").build();
        } catch (URISyntaxException e) {
            throw new ServletException("Could not create post request");
        }

        BasicHttpClientConnectionManager bhcm = new BasicHttpClientConnectionManager(
                GlobalEntries.getGlobalEntries().getConfigManager().getHttpClientSocketRegistry());
        RequestConfig rc = RequestConfig.custom().setCookieSpec(CookieSpecs.STANDARD).build();
        CloseableHttpClient http = HttpClients.custom().setConnectionManager(bhcm).setDefaultRequestConfig(rc)
                .build();

        CloseableHttpResponse httpResp = http.execute(post);

        BufferedReader in = new BufferedReader(new InputStreamReader(httpResp.getEntity().getContent()));

        StringBuffer token = new StringBuffer();

        String line = null;
        while ((line = in.readLine()) != null) {
            token.append(line);
        }

        httpResp.close();
        bhcm.close();

        Gson gson = new Gson();

        Map tokenNVP = com.cedarsoftware.util.io.JsonReader.jsonToMaps(token.toString());

        String accessToken;

        //Store the bearer token for use by Unison
        request.getSession().setAttribute(bearerTokenName, tokenNVP.get("access_token"));

        Map jwtNVP = null;
        LoadUserData loadUser = null;
        try {
            loadUser = (LoadUserData) Class.forName(userLookupClassName).newInstance();
            jwtNVP = loadUser.loadUserAttributesFromIdP(request, response, cfg, authParams, tokenNVP);
        } catch (Exception e) {
            throw new ServletException("Could not load user data", e);
        }

        if (jwtNVP == null) {
            as.setSuccess(false);
        } else {
            if (!linkToDirectory) {
                loadUnlinkedUser(session, noMatchOU, uidAttr, act, jwtNVP, defaultObjectClass);

                as.setSuccess(true);

            } else {
                lookupUser(as, session, myvd, noMatchOU, uidAttr, lookupFilter, act, jwtNVP,
                        defaultObjectClass);
            }

            String redirectToURL = request.getParameter("target");
            if (redirectToURL != null && !redirectToURL.isEmpty()) {
                reqHolder.setURL(redirectToURL);
            }
        }

        holder.getConfig().getAuthManager().nextAuth(request, response, session, false);

    }

}

From source file:org.kuali.rice.ksb.messaging.serviceconnectors.DefaultHttpClientConfigurer.java

/**
 * Configures and builds the RequestConfig for the HttpClient.
 *
 * @return the RequestConfig/*from  www . ja  v  a2s  . co m*/
 */
protected RequestConfig buildRequestConfig() {
    RequestConfig.Builder requestConfigBuilder = RequestConfig.custom();

    // was using "rfc2109" here, but apparently RFC-2956 is standard now.
    requestConfigBuilder.setCookieSpec(COOKIE_POLICY.getValueOrDefault(CookieSpecs.STANDARD));

    Integer connectionRequestTimeout = CONNECTION_MANAGER_TIMEOUT.getValue();
    if (connectionRequestTimeout != null) {
        requestConfigBuilder.setConnectionRequestTimeout(connectionRequestTimeout);
    }

    Integer connectionTimeout = CONNECTION_TIMEOUT.getValue();
    if (connectionTimeout != null) {
        requestConfigBuilder.setConnectTimeout(connectionTimeout);
    }

    Boolean isStaleConnectionCheckEnabled = STALE_CONNECTION_CHECK.getValue();
    if (isStaleConnectionCheckEnabled != null) {
        requestConfigBuilder.setStaleConnectionCheckEnabled(isStaleConnectionCheckEnabled);
    }

    requestConfigBuilder.setSocketTimeout(SO_TIMEOUT.getValueOrDefault(DEFAULT_SOCKET_TIMEOUT));

    Boolean isUseExpectContinue = USE_EXPECT_CONTINUE.getValue();
    if (isUseExpectContinue != null) {
        requestConfigBuilder.setExpectContinueEnabled(isUseExpectContinue);
    }

    Integer maxRedirects = MAX_REDIRECTS.getValue();
    if (maxRedirects != null) {
        requestConfigBuilder.setMaxRedirects(maxRedirects);
    }

    Boolean isCircularRedirectsAllowed = ALLOW_CIRCULAR_REDIRECTS.getValue();
    if (isCircularRedirectsAllowed != null) {
        requestConfigBuilder.setCircularRedirectsAllowed(isCircularRedirectsAllowed);
    }

    Boolean isRejectRelativeRedirects = REJECT_RELATIVE_REDIRECT.getValue();
    if (isRejectRelativeRedirects != null) {
        // negating the parameter value here to align with httpcomponents:
        requestConfigBuilder.setRelativeRedirectsAllowed(!isRejectRelativeRedirects);
    }

    return requestConfigBuilder.build();
}

From source file:com.hp.octane.integrations.services.rest.OctaneRestClientImpl.java

private HttpClientContext createHttpContext(String requestUrl, boolean isLoginRequest) {
    HttpClientContext context = HttpClientContext.create();
    context.setCookieStore(new BasicCookieStore());

    //  add security token if needed
    if (!isLoginRequest) {
        context.getCookieStore().addCookie(LWSSO_TOKEN);
    }// w  w  w . java2s .com

    //  prepare request config
    RequestConfig.Builder requestConfigBuilder = RequestConfig.custom().setCookieSpec(CookieSpecs.STANDARD);

    //  configure proxy if needed
    URL parsedUrl = CIPluginSDKUtils.parseURL(requestUrl);
    CIProxyConfiguration proxyConfiguration = configurer.pluginServices.getProxyConfiguration(parsedUrl);
    if (proxyConfiguration != null) {
        logger.debug("proxy will be used with the following setup: " + proxyConfiguration);
        HttpHost proxyHost = new HttpHost(proxyConfiguration.getHost(), proxyConfiguration.getPort());

        if (proxyConfiguration.getUsername() != null && !proxyConfiguration.getUsername().isEmpty()) {
            AuthScope authScope = new AuthScope(proxyHost);
            Credentials credentials = new UsernamePasswordCredentials(proxyConfiguration.getUsername(),
                    proxyConfiguration.getPassword());
            CredentialsProvider credentialsProvider = new SystemDefaultCredentialsProvider();
            credentialsProvider.setCredentials(authScope, credentials);
            context.setCredentialsProvider(credentialsProvider);
        }
        requestConfigBuilder.setProxy(proxyHost);
    }

    context.setRequestConfig(requestConfigBuilder.build());
    return context;
}

From source file:com.tremolosecurity.proxy.myvd.inserts.restful.OpenUnisonRestful.java

public HttpCon createClient() throws Exception {
    ArrayList<Header> defheaders = new ArrayList<Header>();
    defheaders.add(new BasicHeader("X-Csrf-Token", "1"));

    BasicHttpClientConnectionManager bhcm = new BasicHttpClientConnectionManager(
            GlobalEntries.getGlobalEntries().getConfigManager().getHttpClientSocketRegistry());

    RequestConfig rc = RequestConfig.custom().setCookieSpec(CookieSpecs.STANDARD).setRedirectsEnabled(false)
            .build();//ww w.ja  v  a  2  s.  com

    CloseableHttpClient http = HttpClients.custom().setConnectionManager(bhcm).setDefaultHeaders(defheaders)
            .setDefaultRequestConfig(rc).build();

    HttpCon con = new HttpCon();
    con.setBcm(bhcm);
    con.setHttp(http);

    return con;

}

From source file:de.jetwick.snacktory.HtmlFetcher.java

protected CloseableHttpResponse createUrlConnection(String urlAsStr, int timeout,
        boolean includeSomeGooseOptions, boolean isHead) throws MalformedURLException, IOException {
    CloseableHttpClient httpclient = HttpClients.createDefault();
    HttpRequestBase request = null;//from w ww  .ja v  a 2s  .  c  o m
    if (isHead) {
        request = new HttpHead(urlAsStr);
    } else {
        request = new HttpGet(urlAsStr);
    }
    RequestConfig requestConfig = RequestConfig.custom().setConnectionRequestTimeout(timeout)
            .setConnectTimeout(timeout).setSocketTimeout(timeout).setCookieSpec(CookieSpecs.STANDARD).build();
    request.setHeader("User-Agent", userAgent);
    request.setHeader("Accept", accept);

    if (includeSomeGooseOptions) {
        request.setHeader("Accept-Language", language);
        request.setHeader("content-charset", charset);
        request.setHeader("Referer", referrer);
        // avoid the cache for testing purposes only?
        request.setHeader("Cache-Control", cacheControl);
    }

    // suggest respond to be gzipped or deflated (which is just another compression)
    // http://stackoverflow.com/q/3932117
    request.setHeader("Accept-Encoding", "gzip, deflate");
    request.setConfig(requestConfig);

    return httpclient.execute(request);
}

From source file:org.gtri.fhir.api.vistaex.resource.impl.VistaExResourceImpl.java

/**
 * Creates a {@link CloseableHttpClient} to use in the application
 * @return//from  ww w . jav  a2 s  .  c  o  m
 */
private CloseableHttpClient createHttpClient() {
    //TODO: Fix to use non-deprecated code
    RequestConfig globalConfig = RequestConfig.custom().setCookieSpec(CookieSpecs.STANDARD).build();
    CloseableHttpClient httpClient = HttpClients.custom().setDefaultRequestConfig(globalConfig)
            .setSSLSocketFactory(getSslsf())
            .setHostnameVerifier(SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER).build();
    return httpClient;
}

From source file:com.tremolosecurity.unison.openshiftv3.OpenShiftTarget.java

public HttpCon createClient() throws Exception {
    ArrayList<Header> defheaders = new ArrayList<Header>();
    defheaders.add(new BasicHeader("X-Csrf-Token", "1"));

    BasicHttpClientConnectionManager bhcm = new BasicHttpClientConnectionManager(
            cfgMgr.getHttpClientSocketRegistry());

    RequestConfig rc = RequestConfig.custom().setCookieSpec(CookieSpecs.STANDARD).setRedirectsEnabled(false)
            .build();//  w w w .j a va2 s .  c  o  m

    CloseableHttpClient http = HttpClients.custom().setConnectionManager(bhcm).setDefaultHeaders(defheaders)
            .setDefaultRequestConfig(rc).build();

    HttpCon con = new HttpCon();
    con.setBcm(bhcm);
    con.setHttp(http);

    return con;

}

From source file:org.eclipselabs.garbagecat.Main.java

/**
 * @return version string./*from w  w w.  j  av a 2  s. com*/
 */
private static String getLatestVersion() {
    String url = "https://github.com/mgm3746/garbagecat/releases/latest";
    String name = null;
    try {
        CloseableHttpClient httpClient = HttpClientBuilder.create().build();
        httpClient = HttpClients.custom()
                .setDefaultRequestConfig(RequestConfig.custom().setCookieSpec(CookieSpecs.STANDARD).build())
                .build();
        HttpGet request = new HttpGet(url);
        request.addHeader("Accept", "application/json");
        request.addHeader("content-type", "application/json");
        HttpResponse result = httpClient.execute(request);
        String json = EntityUtils.toString(result.getEntity(), "UTF-8");
        JSONObject jsonObj = new JSONObject(json);
        name = jsonObj.getString("tag_name");
    }

    catch (Exception ex) {
        name = "Unable to retrieve";
        ex.printStackTrace();
    }
    return name;
}

From source file:com.tremolosecurity.unison.openstack.KeystoneProvisioningTarget.java

public HttpCon createClient() throws Exception {
    ArrayList<Header> defheaders = new ArrayList<Header>();

    BasicHttpClientConnectionManager bhcm = new BasicHttpClientConnectionManager(
            cfgMgr.getHttpClientSocketRegistry());

    RequestConfig rc = RequestConfig.custom().setCookieSpec(CookieSpecs.STANDARD).setRedirectsEnabled(false)
            .build();/*from   w  w  w  . j av a  2 s. com*/

    CloseableHttpClient http = HttpClients.custom().setConnectionManager(bhcm).setDefaultHeaders(defheaders)
            .setDefaultRequestConfig(rc).build();

    HttpCon con = new HttpCon();
    con.setBcm(bhcm);
    con.setHttp(http);

    return con;

}