Example usage for javax.servlet.http Cookie setSecure

List of usage examples for javax.servlet.http Cookie setSecure

Introduction

In this page you can find the example usage for javax.servlet.http Cookie setSecure.

Prototype

public void setSecure(boolean flag) 

Source Link

Document

Indicates to the browser whether the cookie should only be sent using a secure protocol, such as HTTPS or SSL.

Usage

From source file:org.jasig.portal.portlet.dao.jpa.PortletCookieImpl.java

@Override
public Cookie toCookie() {
    Cookie cookie = new Cookie(this.name, this.value);
    cookie.setComment(this.comment);
    if (this.domain != null) {
        // FYI: setDomain requires non-null argument (requirement not documented)
        cookie.setDomain(this.domain);
    }//from w  w w  .  java2s .  c  om

    final int maxAge;
    if (this.expires == null) {
        maxAge = -1;
    } else {
        maxAge = (int) TimeUnit.MILLISECONDS.toSeconds(this.expires.getTime() - System.currentTimeMillis());
    }
    cookie.setMaxAge(maxAge);
    cookie.setPath(this.path);
    cookie.setSecure(this.secure);
    cookie.setVersion(this.version);
    return cookie;
}

From source file:de.innovationgate.wga.server.api.Call.java

/**
 * Creates a new completely initialized HTTP cookie, which is not yet assigned to the call.
 * Use {@link #addCookie(Cookie)} to do so and send it to the client.
 * The cookie is initialized with path (the OpenWGA context path), type/maxage (transient),
 * domain (either request host or host from configured server base url) and security
 * flag (true if the current call is HTTPS).
 * @param name Name of the cookie//from  w  w  w .j a  v a  2  s  . c o  m
 * @param value Value of the cookie
 * @return
 * @throws WGException
 */
public Cookie createCookie(String name, String value) throws WGException {

    URLBuilder baseURL = _wga.urlBuilder(_wga.server().getBaseURL());
    URLBuilder requestURL = _wga.urlBuilder(getURL());

    Cookie c = new Cookie();
    c.setName(name);
    c.setValue(value);
    c.setMaxAge(-1);
    c.setPath(baseURL.build(false));
    if (_wga.isRequestAvailable()) {
        c.setDomain(requestURL.getHost());
    } else {
        c.setDomain(baseURL.getHost());
    }
    c.setSecure(requestURL.getProtocol().equals("https"));

    return c;

}

From source file:uk.ac.ox.webauth.FilterWorker.java

/**
 * Set a proxy cookie authenticating the user to this WAS.
 * @param   webauthr    The users WEBAUTHR token.
 * @param   privateKey  The private WAS key to encrypt the proxy cookie with.
 * @param   response    The response object to send the cookie to.
 *//*from   w  w  w.  ja  v a 2 s  .  c  om*/
private void setProxyCookie(Token webauthr, WebauthKey privateKey, HttpServletResponse response)
        throws ServletException {
    // if the webauthr token is a proxy token then set a cookie containing it
    if (!"proxy".equals(webauthr.getString("t"))) {
        return;
    }
    String encrypted = null;
    try {
        encrypted = webauthr.encrypt(privateKey.key());
    } catch (GeneralSecurityException gse) {
        throw new ServletException("Could not encrypt proxy-token.", gse);
    }
    Cookie webauth_pt = new Cookie("webauth_pt_" + webauthr.getString("pt"), encrypted);
    webauth_pt.setMaxAge(-1);
    webauth_pt.setSecure(true);
    webauth_pt.setPath("/");
    response.addCookie(webauth_pt);
    cookies.put(webauth_pt.getName(), webauth_pt);
}

From source file:org.kuali.mobility.shared.controllers.HomeController.java

/**
 * Controller method for the preference screen
 *//*from  w  w  w . ja  v  a  2s.  c  om*/
@RequestMapping(value = "preferences", method = RequestMethod.GET)
public String preferences(@CookieValue(value = "homeLayout", required = false) String homeLayoutCookie,
        @RequestParam(value = "homeLayout", required = false) String homeLayoutParam,
        HttpServletRequest request, HttpServletResponse response, Model uiModel) {
    User user = (User) request.getSession().getAttribute(Constants.KME_USER_KEY);
    String homeToolName = "home";
    List<Campus> campuses = getCampusService().findCampusesByTool(homeToolName);
    List<HomeScreen> homeScreens = getAdminService().getAllHomeScreens();

    String currentLayout = homeLayoutCookie;

    boolean useSecureCookie = Boolean
            .parseBoolean(this.getKmeProperties().getProperty("kme.secure.cookie", "false"));
    // Change layout if requested
    if (!StringUtils.isEmpty(homeLayoutParam)) {
        currentLayout = LayoutUtil.getValidLayout(homeLayoutParam, kmeProperties);
        Cookie layoutCookie = new Cookie("homeLayout", currentLayout);
        int cookieMaxAge = Integer.parseInt(getKmeProperties().getProperty("cookie.max.age", "3600"));
        layoutCookie.setMaxAge(cookieMaxAge); // default one hour, should implement in kme.config.properties.
        layoutCookie.setPath(request.getContextPath());
        layoutCookie.setSecure(useSecureCookie);
        response.addCookie(layoutCookie);
    }

    // Determine current home layout
    boolean allowLayoutChange = false;
    if (kmeProperties != null) {
        allowLayoutChange = Boolean
                .parseBoolean(kmeProperties.getProperty("home.layout.userEditable", "false"));
        if (allowLayoutChange) {
            currentLayout = LayoutUtil.getValidLayout(currentLayout, kmeProperties);
            uiModel.addAttribute("currentLayout", currentLayout);
            uiModel.addAttribute("availableLayouts", HomeScreen.LAYOUTS);
        }
    }

    List<Sender> senders = senderService.findAllUnhiddenSenders();

    // Add attributes to model
    uiModel.addAttribute("senders", senders);
    uiModel.addAttribute("toolName", homeToolName);
    uiModel.addAttribute("campuses", campuses);
    uiModel.addAttribute("homeScreens", homeScreens);
    uiModel.addAttribute("user", user);
    uiModel.addAttribute("supportedLanguages", getSupportedLanguages());
    uiModel.addAttribute("allowLayoutChange", allowLayoutChange);
    if ("3".equalsIgnoreCase(getKmeProperties().getProperty("kme.uiVersion", "classic"))) {
        return "ui3/home/preferences";
    }
    return "preferences";
}

From source file:com.streamsets.lib.security.http.SSOUserAuthenticator.java

Cookie createAuthCookie(HttpServletRequest httpReq, String authToken, long expiresMillis) {
    Cookie authCookie = new Cookie(getAuthCookieName(httpReq), authToken);
    authCookie.setPath("/");
    // if positive it is a persistent session, else a transient one and we don't have to set the cookie age
    if (expiresMillis > 0) {
        int secondsToLive = (int) ((expiresMillis - System.currentTimeMillis()) / 1000);
        authCookie.setMaxAge(secondsToLive);
    } else if (expiresMillis == 0) {
        // to delete the cookie
        authCookie.setMaxAge(0);//from w w  w  .j a  va 2 s.c om
    }

    if (isDataCollector) {
        // When an SDC is accessing SCH, set the cookie based on the SDC's scheme
        authCookie.setSecure(httpReq.isSecure());
    } else {
        // When a browser accesses SCH, set the cookie based on the SCH endpoint
        authCookie.setSecure(dpmBaseUrl.startsWith("https"));
    }

    return authCookie;
}

From source file:com.tremolosecurity.proxy.filters.PreAuthFilter.java

@Override
public void doFilter(HttpFilterRequest request, HttpFilterResponse response, HttpFilterChain chain)
        throws Exception {
    AuthInfo userData = ((AuthController) request.getSession().getAttribute(ProxyConstants.AUTH_CTL))
            .getAuthInfo();//  w w  w.j a  va 2  s.c o  m
    ConfigManager cfg = (ConfigManager) request.getAttribute(ProxyConstants.TREMOLO_CFG_OBJ);

    List<Cookie> cookies = null;

    if (userData.getAuthLevel() > 0 && userData.isAuthComplete()) {
        UrlHolder holder = (UrlHolder) request.getAttribute(ProxyConstants.AUTOIDM_CFG);
        HttpSession session = request.getSession();
        String uid = (String) session.getAttribute("TREMOLO_PRE_AUTH");
        if (uid == null || !uid.equals(userData.getUserDN())) {
            session.setAttribute("TREMOLO_PRE_AUTH", userData.getUserDN());
            HashMap<String, String> uriParams = new HashMap<String, String>();
            uriParams.put("fullURI", this.uri);

            UrlHolder remHolder = cfg.findURL(this.url);

            org.apache.http.client.methods.HttpRequestBase method = null;

            if (this.postSAML) {
                PrivateKey pk = holder.getConfig().getPrivateKey(this.keyAlias);
                java.security.cert.X509Certificate cert = holder.getConfig().getCertificate(this.keyAlias);

                Saml2Assertion assertion = new Saml2Assertion(
                        userData.getAttribs().get(this.nameIDAttribute).getValues().get(0), pk, cert, null,
                        this.issuer, this.assertionConsumerURL, this.audience, this.signAssertion,
                        this.signResponse, false, this.nameIDType, this.authnCtxClassRef);

                String respXML = "";

                try {
                    respXML = assertion.generateSaml2Response();
                } catch (Exception e) {
                    throw new ServletException("Could not generate SAMLResponse", e);
                }

                List<NameValuePair> formparams = new ArrayList<NameValuePair>();
                String base64 = Base64.encodeBase64String(respXML.getBytes("UTF-8"));

                formparams.add(new BasicNameValuePair("SAMLResponse", base64));
                if (this.relayState != null && !this.relayState.isEmpty()) {
                    formparams.add(new BasicNameValuePair("RelayState", this.relayState));
                }

                UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formparams, "UTF-8");
                HttpPost post = new HttpPost(this.assertionConsumerURL);
                post.setEntity(entity);
                method = post;

            } else {
                HttpGet get = new HttpGet(remHolder.getProxyURL(uriParams));
                method = get;
            }

            LastMileUtil.addLastMile(cfg, userData.getAttribs().get(loginAttribute).getValues().get(0),
                    this.loginAttribute, method, lastMileKeyAlias, true);
            BasicHttpClientConnectionManager bhcm = new BasicHttpClientConnectionManager(
                    cfg.getHttpClientSocketRegistry());
            try {
                CloseableHttpClient httpclient = HttpClients.custom().setConnectionManager(bhcm)
                        .setDefaultRequestConfig(cfg.getGlobalHttpClientConfig()).build();

                HttpResponse resp = httpclient.execute(method);

                if (resp.getStatusLine().getStatusCode() == 500) {
                    BufferedReader in = new BufferedReader(
                            new InputStreamReader(resp.getEntity().getContent()));
                    StringBuffer error = new StringBuffer();
                    String line = null;
                    while ((line = in.readLine()) != null) {
                        error.append(line).append('\n');
                    }

                    logger.warn("Pre-Auth Failed : " + error);
                }

                org.apache.http.Header[] headers = resp.getAllHeaders();

                StringBuffer stmp = new StringBuffer();

                cookies = new ArrayList<Cookie>();

                for (org.apache.http.Header header : headers) {
                    if (header.getName().equalsIgnoreCase("set-cookie")
                            || header.getName().equalsIgnoreCase("set-cookie2")) {
                        //System.out.println(header.getValue());
                        String cookieVal = header.getValue();
                        /*if (cookieVal.endsWith("HttpOnly")) {
                           cookieVal = cookieVal.substring(0,cookieVal.indexOf("HttpOnly"));
                        }
                                
                        //System.out.println(cookieVal);*/

                        List<HttpCookie> cookiesx = HttpCookie.parse(cookieVal);
                        for (HttpCookie cookie : cookiesx) {

                            String cookieFinalName = cookie.getName();
                            if (cookieFinalName.equalsIgnoreCase("JSESSIONID")) {
                                stmp.setLength(0);
                                stmp.append("JSESSIONID").append('-')
                                        .append(holder.getApp().getName().replaceAll(" ", "|"));
                                cookieFinalName = stmp.toString();
                            }

                            //logger.info("Adding cookie name '" + cookieFinalName + "'='" + cookie.getValue() + "'");

                            Cookie respcookie = new Cookie(cookieFinalName, cookie.getValue());
                            respcookie.setComment(cookie.getComment());
                            if (cookie.getDomain() != null) {
                                //respcookie.setDomain(cookie.getDomain());
                            }
                            respcookie.setMaxAge((int) cookie.getMaxAge());
                            respcookie.setPath(cookie.getPath());

                            respcookie.setSecure(cookie.getSecure());
                            respcookie.setVersion(cookie.getVersion());
                            cookies.add(respcookie);

                            if (request.getCookieNames().contains(respcookie.getName())) {
                                request.removeCookie(cookieFinalName);
                            }

                            request.addCookie(new Cookie(cookie.getName(), cookie.getValue()));
                        }
                    }
                }

            } finally {
                bhcm.shutdown();
            }
        }
    }

    chain.nextFilter(request, response, chain);
    if (cookies != null) {

        for (Cookie cookie : cookies) {

            response.addCookie(cookie);
        }
    }

}

From source file:org.josso.gateway.signon.SignonBaseAction.java

/**
 * Stores session id/*  w ww  . ja  va  2  s.  c  o  m*/
 *
 * @param request http request
 * @param session SSO session instance
 */
protected void storeSSOInformation(HttpServletRequest request, HttpServletResponse response,
        SSOSession session) {
    MutableSSOContext ctx = (MutableSSOContext) SSOContext.getCurrent();
    ctx.setCurrentSession(session);

    try {
        SSOWebConfiguration cfg = Lookup.getInstance().lookupSSOWebConfiguration();

        if (cfg.isSessionTokenOnClient()) {
            logger.debug("Storing SSO Session ID on clinet");
            Cookie ssoCookie = newJossoCookie(request.getContextPath(),
                    JOSSO_SINGLE_SIGN_ON_COOKIE + "_" + ctx.getSecurityDomain().getName(), session.getId());
            response.addCookie(ssoCookie);
        } else {
            logger.debug("Storing SSO Session ID on server");
            HttpSession hsession = request.getSession();
            hsession.setAttribute(JOSSO_SINGLE_SIGN_ON_COOKIE + "_" + ctx.getSecurityDomain().getName(),
                    session.getId());
        }

        logger.debug("Remember Me:"
                + request.getParameter(org.josso.gateway.signon.Constants.PARAM_JOSSO_REMEMBERME));
        logger.debug("Command:" + request.getParameter(org.josso.gateway.signon.Constants.PARAM_JOSSO_CMD));

        // Remember user authentication.
        if (cfg.isRememberMeEnabled()
                && request.getParameter(org.josso.gateway.signon.Constants.PARAM_JOSSO_REMEMBERME) != null) {

            // Storing remember me information (always on client)
            logger.debug("Storing SSO Rememberme Token on Client");

            String cipherSuite = (String) request.getAttribute("javax.servlet.request.cipher_suite");

            if (cipherSuite == null)
                logger.error("SSL Required for 'remember me' feature");

            // We need this auth scheme to build the proper token
            // TODO : Check this when implementing the "Password Recovery" becauase it's a similar case.  We will have to acces the password value from the store
            RememberMeAuthScheme scheme = (RememberMeAuthScheme) ctx.getSecurityDomain().getAuthenticator()
                    .getAuthenticationScheme("rememberme-authentication");
            String token = scheme.getRemembermeTokenForUser(session.getUsername());

            // This will provide the credential string value ...
            Cookie rememberMeCookie = new Cookie(
                    JOSSO_REMEMBERME_TOKEN + "_" + ctx.getSecurityDomain().getName(), token);

            // If max age was not specified, assume a year.
            rememberMeCookie.setMaxAge(
                    60 * (cfg.getRememberMeMaxAge() > 0 ? cfg.getRememberMeMaxAge() : 60 * 24 * 365)); // The cookie will live for a year ...

            rememberMeCookie.setPath("/");
            if (cfg.isSessionTokenSecure()) {
                rememberMeCookie.setSecure(true);
            } else {
                logger.error("Remember Me funcion requires SSL Transport!");
            }

            // Store cookie in response
            response.addCookie(rememberMeCookie);

        }

    } catch (Exception ex) {
        logger.error("Error while storing SSO Information : " + ex.getMessage(), ex);
    }

}

From source file:cn.tiup.httpproxy.ProxyServlet.java

/** Copy cookie from the proxy to the servlet client.
 *  Replaces cookie path to local path and renames cookie to avoid collisions.
 *///  ww w . ja v  a 2s. c  om
protected void copyProxyCookie(HttpServletRequest servletRequest, HttpServletResponse servletResponse,
        String headerValue) {
    List<HttpCookie> cookies = HttpCookie.parse(headerValue);

    for (HttpCookie cookie : cookies) {
        //set cookie name prefixed w/ a proxy value so it won't collide w/ other cookies
        String proxyCookieName = getCookieNamePrefix(cookie.getName()) + cookie.getName();
        Cookie servletCookie = new Cookie(proxyCookieName, cookie.getValue());
        servletCookie.setComment(cookie.getComment());
        servletCookie.setMaxAge((int) cookie.getMaxAge());
        servletCookie.setPath(cookie.getPath()); //set to the path of the proxy servlet
        // don't set cookie domain
        servletCookie.setSecure(cookie.getSecure());
        servletCookie.setVersion(cookie.getVersion());
        servletResponse.addCookie(servletCookie);
    }
}

From source file:io.hops.hopsworks.api.kibana.ProxyServlet.java

/**
 * Copy cookie from the proxy to the servlet client.
 * Replaces cookie path to local path and renames cookie to avoid collisions.
 *///from   ww w  .ja  v a  2  s  .c o  m
protected void copyProxyCookie(HttpServletRequest servletRequest, HttpServletResponse servletResponse,
        String header) {
    List<HttpCookie> cookies = HttpCookie.parse(header);
    String path = servletRequest.getContextPath(); // path starts with / or is empty string
    path += servletRequest.getServletPath(); // servlet path starts with / or is empty string

    for (HttpCookie cookie : cookies) {
        //set cookie name prefixed w/ a proxy value so it won't collide w/ other cookies
        String proxyCookieName = getCookieNamePrefix() + cookie.getName();
        Cookie servletCookie = new Cookie(proxyCookieName, cookie.getValue());
        servletCookie.setComment(cookie.getComment());
        servletCookie.setMaxAge((int) cookie.getMaxAge());
        servletCookie.setPath(path); //set to the path of the proxy servlet
        // don't set cookie domain
        servletCookie.setSecure(cookie.getSecure());
        servletCookie.setVersion(cookie.getVersion());
        servletResponse.addCookie(servletCookie);
    }
}