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:net.shopxx.util.CookieUtils.java

/**
 * cookie/* ww  w .j  a  v a2s  .  c  o  m*/
 * 
 * @param request
 *            HttpServletRequest
 * @param response
 *            HttpServletResponse
 * @param name
 *            cookie??
 * @param value
 *            cookie
 * @param path
 *            
 * @param maxAge
 *            (??: )
 * @param domain
 *            
 * @param secure
 *            ??
 */
public static void addCookie(HttpServletRequest request, HttpServletResponse response, String name,
        String value, String path, Integer maxAge, String domain, Boolean secure) {
    Assert.notNull(request);
    Assert.notNull(response);
    Assert.hasText(name);
    try {
        value = URLEncoder.encode(value, "UTF-8");
        Cookie cookie = new Cookie(name, value);
        if (StringUtils.isNotEmpty(path)) {
            cookie.setPath(path);
        }
        if (maxAge != null) {
            cookie.setMaxAge(maxAge);
        }
        if (StringUtils.isNotEmpty(domain)) {
            cookie.setDomain(domain);
        }
        if (secure != null) {
            cookie.setSecure(secure);
        }
        response.addCookie(cookie);
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    }
}

From source file:com.anjz.util.CookieUtils.java

private static void setCookie(String key, String value, int maxAge, String path, String domainName,
        final boolean httpOnly, final boolean secure, HttpServletResponse response) {
    if (response != null) {
        Cookie cookie = new Cookie(key, value);
        cookie.setMaxAge(maxAge);//from  w ww.  ja v a2s  .  co  m
        if (StringUtils.isNotBlank(path)) {
            cookie.setPath(path);
        } else {
            cookie.setPath(PATH);
        }
        if (StringUtils.isNotBlank(domainName)) {
            cookie.setDomain(domainName);
        }
        cookie.setVersion(0);
        cookie.setSecure(secure);
        if (httpOnly) {
            final StringBuffer buf = new StringBuffer();
            getCookieHeaderValue(cookie, buf, httpOnly);
            response.addHeader(getCookieHeaderName(cookie), buf.toString());
        } else {
            response.addCookie(cookie);
        }
    }
}

From source file:org.jahia.params.valves.CookieAuthValveImpl.java

public static void createAndSendCookie(AuthValveContext authContext, JCRUserNode theUser,
        CookieAuthConfig cookieAuthConfig) {
    // now let's look for a free random cookie value key.
    String cookieUserKey = CookieAuthValveImpl.getAvailableCookieKey(cookieAuthConfig);
    // let's save the identifier for the user in the database
    try {//from   ww  w .j  a  v  a 2  s  .c o m
        theUser.setProperty(cookieAuthConfig.getUserPropertyName(), cookieUserKey);
        theUser.getSession().save();
    } catch (RepositoryException e) {
        logger.error(e.getMessage(), e);
    }
    // now let's save the same identifier in the cookie.
    String realm = theUser.getRealm();
    Cookie authCookie = new Cookie(cookieAuthConfig.getCookieName(),
            cookieUserKey + (realm != null ? (":" + realm) : ""));
    authCookie.setPath(StringUtils.isNotEmpty(authContext.getRequest().getContextPath())
            ? authContext.getRequest().getContextPath()
            : "/");
    authCookie.setMaxAge(cookieAuthConfig.getMaxAgeInSeconds());
    authCookie.setHttpOnly(cookieAuthConfig.isHttpOnly());
    authCookie.setSecure(cookieAuthConfig.isSecure());
    authContext.getResponse().addCookie(authCookie);
}

From source file:com.iterzp.momo.utils.WebUtils.java

/**
 * cookie/*from   ww w.ja  v  a 2 s.  c  om*/
 * 
 * @param request
 *            HttpServletRequest
 * @param response
 *            HttpServletResponse
 * @param name
 *            cookie??
 * @param value
 *            cookie
 * @param maxAge
 *            (??: )
 * @param path
 *            
 * @param domain
 *            
 * @param secure
 *            ??
 */
public static void addCookie(HttpServletRequest request, HttpServletResponse response, String name,
        String value, Integer maxAge, String path, String domain, Boolean secure) {
    Assert.notNull(request);
    Assert.notNull(response);
    Assert.hasText(name);
    try {
        name = URLEncoder.encode(name, "UTF-8");
        value = URLEncoder.encode(value, "UTF-8");
        Cookie cookie = new Cookie(name, value);
        if (maxAge != null) {
            cookie.setMaxAge(maxAge);
        }
        if (StringUtils.isNotEmpty(path)) {
            cookie.setPath(path);
        }
        if (StringUtils.isNotEmpty(domain)) {
            cookie.setDomain(domain);
        }
        if (secure != null) {
            cookie.setSecure(secure);
        }
        response.addCookie(cookie);
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    }
}

From source file:com.vmware.identity.openidconnect.sample.RelyingPartyController.java

private static Cookie logoutSessionCookie() {
    Cookie sessionCookie = new Cookie(SESSION_COOKIE_NAME, "");
    sessionCookie.setPath("/openidconnect-sample-rp");
    sessionCookie.setSecure(true);
    sessionCookie.setHttpOnly(true);/*w w w  .  j a  va 2s .c o  m*/
    sessionCookie.setMaxAge(0);
    return sessionCookie;
}

From source file:org.wso2.carbon.ui.CarbonUILoginUtil.java

/**
 * //from   w  w w .j  a  v  a 2  s .  co  m
 * @param authenticator
 * @param request
 * @param response
 * @param session
 * @param authenticated
 * @param contextPath
 * @param indexPageURL
 * @param httpLogin
 * @return
 * @throws IOException
 */
protected static boolean handleLogout(CarbonUIAuthenticator authenticator, HttpServletRequest request,
        HttpServletResponse response, HttpSession session, boolean authenticated, String contextPath,
        String indexPageURL, String httpLogin) throws IOException {
    log.debug("Handling Logout..");
    // Logout the user from the back-end
    try {
        authenticator = (CarbonUIAuthenticator) session
                .getAttribute(CarbonSecuredHttpContext.CARBON_AUTHNETICATOR);
        if (authenticator != null) {
            authenticator.unauthenticate(request);
            log.debug("Backend session invalidated");
        }
    } catch (Exception e) {
        log.error(e.getMessage(), e);
        response.sendRedirect("../admin/login.jsp");
        return false;
    }

    // Only applicable if this is SAML2 based SSO. Complete the logout action after receiving
    // the Logout response.
    if ("true".equals(request.getParameter("logoutcomplete"))) {
        HttpSession currentSession = request.getSession(false);
        if (currentSession != null) {
            // check if current session has expired
            session.removeAttribute(CarbonSecuredHttpContext.LOGGED_USER);
            session.getServletContext().removeAttribute(CarbonSecuredHttpContext.LOGGED_USER);
            try {
                session.invalidate();
            } catch (Exception ignored) { // Ignore exception when
                // invalidating and
                // invalidated session
            }
            log.debug("Frontend session invalidated");
        }
        response.sendRedirect("../../carbon/admin/login.jsp");
        return false;
    }

    if (request.getAttribute("ExternalLogoutPage") != null) {
        HttpSession currentSession = request.getSession(false);
        if (currentSession != null) {
            session.removeAttribute("logged-user");
            session.getServletContext().removeAttribute("logged-user");
            try {
                session.invalidate();
            } catch (Exception ignored) {
            }
            log.debug("Frontend session invalidated");
        }

        response.sendRedirect((String) request.getAttribute("ExternalLogoutPage"));
        return false;
    }

    CarbonSSOSessionManager ssoSessionManager = CarbonSSOSessionManager.getInstance();

    if (!ssoSessionManager.skipSSOSessionInvalidation(request, authenticator)
            && !ssoSessionManager.isSessionValid(request.getSession().getId())) {
        HttpSession currentSession = request.getSession(false);
        if (currentSession != null) {
            // check if current session has expired
            session.removeAttribute(CarbonSecuredHttpContext.LOGGED_USER);
            session.getServletContext().removeAttribute(CarbonSecuredHttpContext.LOGGED_USER);
            try {
                session.invalidate();
                log.debug("SSO session session invalidated ");
            } catch (Exception ignored) { // Ignore exception when
                // Invalidating and invalidated session
                if (log.isDebugEnabled()) {
                    log.debug("Ignore exception when invalidating session", ignored);
                }
            }
        }
        response.sendRedirect("../.." + indexPageURL);
        return false;
    }

    // Memory clean up : remove invalid session from the invalid session list.
    ssoSessionManager.removeInvalidSession(request.getSession().getId());

    // This condition is evaluated when users are logged out in SAML2 based SSO
    if (request.getAttribute("logoutRequest") != null) {
        log.debug("Loging out from SSO session");
        response.sendRedirect("../../carbon/sso-acs/redirect_ajaxprocessor.jsp?logout=true");
        return false;
    }

    HttpSession currentSession = request.getSession(false);
    if (currentSession != null) {
        // Check if current session has expired
        session.removeAttribute(CarbonSecuredHttpContext.LOGGED_USER);
        session.getServletContext().removeAttribute(CarbonSecuredHttpContext.LOGGED_USER);
        try {
            session.invalidate();
            log.debug("Frontend session invalidated");
        } catch (Exception ignored) {
            // Ignore exception when invalidating and invalidated session
        }
    }

    Cookie rmeCookie = new Cookie(CarbonConstants.REMEMBER_ME_COOKE_NAME, null);
    rmeCookie.setPath("/");
    rmeCookie.setSecure(true);
    rmeCookie.setMaxAge(0);
    response.addCookie(rmeCookie);
    response.sendRedirect(contextPath + indexPageURL);
    return false;
}

From source file:com.vmware.identity.openidconnect.sample.RelyingPartyController.java

private static Cookie loginSessionCookie(SessionID sessionId) {
    Cookie sessionCookie = new Cookie(SESSION_COOKIE_NAME, sessionId.getValue());
    sessionCookie.setPath("/openidconnect-sample-rp");
    sessionCookie.setSecure(true);
    sessionCookie.setHttpOnly(true);/*from  w w w  . j  a v  a 2s . c o m*/
    return sessionCookie;
}

From source file:org.wso2.carbon.ui.CarbonUILoginUtil.java

/**
 * //from www  . j a va2s .co  m
 * @param authenticator
 * @param request
 * @param response
 * @param session
 * @param authenticated
 * @param contextPath
 * @param indexPageURL
 * @param httpLogin
 * @return
 * @throws IOException
 */
protected static boolean handleLogin(CarbonUIAuthenticator authenticator, HttpServletRequest request,
        HttpServletResponse response, HttpSession session, boolean authenticated, String contextPath,
        String indexPageURL, String httpLogin) throws IOException {
    try {

        // commenting out this method as it is not required
        //           String[] username = (String[])request.getParameterMap().get(AbstractCarbonUIAuthenticator.USERNAME);
        //           if(username != null && !username[0].contains("/") && UserUtils.hasMultipleUserStores()){
        //               response.sendRedirect("../../carbon/admin/login.jsp?loginStatus=false&errorCode=domain.not.specified");
        //               return false;
        //           }

        authenticator.authenticate(request);
        session = request.getSession();
        session.setAttribute(CarbonSecuredHttpContext.CARBON_AUTHNETICATOR, authenticator);

        // Check if the username is of type bob@acme.com if so, this is a login from a
        // multi-tenant deployment
        // The tenant id part(i.e. acme.com) should be set into http session for further UI
        // related processing
        String userName = (String) request.getAttribute(AbstractCarbonUIAuthenticator.USERNAME);

        if (log.isDebugEnabled()) {
            log.debug("Login request from " + userName);
        }
        String tenantDomain = null;
        if (request.getAttribute(MultitenantConstants.TENANT_DOMAIN) != null) {
            tenantDomain = (String) request.getAttribute(MultitenantConstants.TENANT_DOMAIN);

        }
        if (tenantDomain == null) {
            tenantDomain = MultitenantUtils.getTenantDomain(userName);
        }
        if (tenantDomain != null && !MultitenantConstants.SUPER_TENANT_DOMAIN_NAME.equals(tenantDomain)) {
            // we will add it to the context
            contextPath += "/" + MultitenantConstants.TENANT_AWARE_URL_PREFIX + "/" + tenantDomain;
        }

        String value = request.getParameter("rememberMe");
        boolean isRememberMe = false;
        if (value != null && value.equals("rememberMe")) {
            isRememberMe = true;
        }

        try {
            if (isRememberMe) {
                String rememberMeCookieValue = (String) request
                        .getAttribute(CarbonConstants.REMEMBER_ME_COOKIE_VALUE);
                int age = Integer
                        .parseInt((String) request.getAttribute(CarbonConstants.REMEMBER_ME_COOKIE_AGE));

                Cookie rmeCookie = new Cookie(CarbonConstants.REMEMBER_ME_COOKE_NAME, rememberMeCookieValue);
                rmeCookie.setPath("/");
                rmeCookie.setSecure(true);
                rmeCookie.setMaxAge(age);
                response.addCookie(rmeCookie);
            }
        } catch (Exception e) {
            response.sendRedirect(contextPath + indexPageURL + (indexPageURL.indexOf('?') == -1 ? "?" : "&")
                    + "loginStatus=false");
            if (log.isDebugEnabled()) {
                log.debug("Security check failed for login request for " + userName);
            }
            return false;
        }
        if (contextPath != null) {
            if (indexPageURL.startsWith("../..")) {
                indexPageURL = indexPageURL.substring(5);
            }

            response.sendRedirect(contextPath + indexPageURL + (indexPageURL.indexOf('?') == -1 ? "?" : "&")
                    + "loginStatus=true");
        }

    } catch (AuthenticationException e) {
        log.debug("Authentication failure ...", e);
        try {
            request.getSession().invalidate();
            getAuthenticator(request).unauthenticate(request);
            if (httpLogin != null) {
                response.sendRedirect(httpLogin + "?loginStatus=false");
                return false;
            } else {
                response.sendRedirect("/carbon/admin/login.jsp?loginStatus=false");
                return false;
            }
        } catch (Exception e1) {
            // ignore exception 
        }

    } catch (Exception e) {
        log.error("error occurred while login", e);
        response.sendRedirect("../../carbon/admin/login.jsp?loginStatus=failed");
    }

    return false;
}

From source file:org.carewebframework.ui.FrameworkWebSupport.java

/**
 * Sets a cookie into the response. Cookies are URLEncoded for consistency (Version 0+ of
 * Cookies)/*ww w  . ja v a2  s .  c  o  m*/
 * 
 * @param cookieName Name of cookie.
 * @param value Value of cookie. If null, the cookie is removed from the client if it exists.
 * @param httpResponse Response object.
 * @param httpRequest Request object.
 * @return Newly created cookie.
 * @throws IllegalArgumentException if cookieName, httpResponse, or httpRequest arguments are
 *             null
 */
public static Cookie setCookie(final String cookieName, String value, final HttpServletResponse httpResponse,
        final HttpServletRequest httpRequest) {
    Validate.notNull(httpResponse, "The httpResponse must not be null");
    Cookie cookie = getCookie(cookieName, httpRequest);
    if (value != null) {
        value = encodeCookieValue(value);
    }

    if (cookie == null) {
        if (value == null) {
            return null;
        }
        cookie = new Cookie(cookieName, value);
    } else if (value == null) {
        cookie.setMaxAge(0);
    } else {
        cookie.setValue(value);
    }

    if (httpRequest.isSecure()) {
        cookie.setSecure(true);
    }

    httpResponse.addCookie(cookie);
    return cookie;
}

From source file:com.google.gsa.valve.modules.utils.CookieManagement.java

/**
 * Transforms Apache cookies into Servlet Cookies
 * /*from www  . j  av  a 2s.  c om*/
 * @param apacheCookie apache cookie 
 * 
 * @return servlet cookie
 */
public static javax.servlet.http.Cookie transformApacheCookie(
        org.apache.commons.httpclient.Cookie apacheCookie) {

    javax.servlet.http.Cookie newCookie = null;

    if (apacheCookie != null) {
        Date expire = apacheCookie.getExpiryDate();
        int maxAge = -1;

        if (expire == null) {
            maxAge = -1;
        } else {
            Date now = Calendar.getInstance().getTime();
            // Convert milli-second to second
            Long second = new Long((expire.getTime() - now.getTime()) / 1000);
            maxAge = second.intValue();
        }

        newCookie = new javax.servlet.http.Cookie(apacheCookie.getName(), apacheCookie.getValue());
        //Hardcoding the domain
        newCookie.setDomain(apacheCookie.getDomain());
        newCookie.setPath(apacheCookie.getPath());
        newCookie.setMaxAge(maxAge);
        newCookie.setSecure(apacheCookie.getSecure());
    }
    return newCookie;
}