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:com.twelve.capital.external.feed.util.HttpImpl.java

protected Cookie toServletCookie(org.apache.commons.httpclient.Cookie commonsCookie) {

    Cookie cookie = new Cookie(commonsCookie.getName(), commonsCookie.getValue());

    if (!PropsValues.SESSION_COOKIE_USE_FULL_HOSTNAME) {
        String domain = commonsCookie.getDomain();

        if (Validator.isNotNull(domain)) {
            cookie.setDomain(domain);//w w w .j  a v  a  2  s.  com
        }
    }

    Date expiryDate = commonsCookie.getExpiryDate();

    if (expiryDate != null) {
        int maxAge = (int) (expiryDate.getTime() - System.currentTimeMillis());

        maxAge = maxAge / 1000;

        if (maxAge > -1) {
            cookie.setMaxAge(maxAge);
        }
    }

    String path = commonsCookie.getPath();

    if (Validator.isNotNull(path)) {
        cookie.setPath(path);
    }

    cookie.setSecure(commonsCookie.getSecure());
    cookie.setVersion(commonsCookie.getVersion());

    return cookie;
}

From source file:org.owasp.esapi.reference.DefaultHTTPUtilities.java

/**
* {@inheritDoc}// ww w . java 2 s  .c om
 * This implementation uses a custom "set-cookie" header rather than Java's
 * cookie interface which doesn't allow the use of HttpOnly. Configure the
 * HttpOnly and Secure settings in ESAPI.properties.
*/
public void addCookie(HttpServletResponse response, Cookie cookie) {
    String name = cookie.getName();
    String value = cookie.getValue();
    int maxAge = cookie.getMaxAge();
    String domain = cookie.getDomain();
    String path = cookie.getPath();
    boolean secure = cookie.getSecure();

    // validate the name and value
    ValidationErrorList errors = new ValidationErrorList();
    String cookieName = ESAPI.validator().getValidInput("cookie name", name, "HTTPCookieName", 50, false,
            errors);
    String cookieValue = ESAPI.validator().getValidInput("cookie value", value, "HTTPCookieValue", 5000, false,
            errors);

    // if there are no errors, then set the cookie either with a header or normally
    if (errors.size() == 0) {
        if (ESAPI.securityConfiguration().getForceHttpOnlyCookies()) {
            String header = createCookieHeader(cookieName, cookieValue, maxAge, domain, path, secure);
            addHeader(response, "Set-Cookie", header);
        } else {
            // Issue 23 - If the ESAPI Configuration is set to force secure cookies, force the secure flag on the cookie before setting it
            cookie.setSecure(secure || ESAPI.securityConfiguration().getForceSecureCookies());
            response.addCookie(cookie);
        }
        return;
    }
    logger.warning(Logger.SECURITY_FAILURE,
            "Attempt to add unsafe data to cookie (skip mode). Skipping cookie and continuing.");
}

From source file:org.sakaiproject.util.RequestFilter.java

/**
 * Filter a request / response.//from  w  ww. ja v  a2  s .  c om
 */
public void doFilter(ServletRequest requestObj, ServletResponse responseObj, FilterChain chain)
        throws IOException, ServletException {
    StringBuffer sb = null;
    long startTime = System.currentTimeMillis();

    // bind some preferences as "current"
    Boolean curRemoteUser = (Boolean) ThreadLocalManager.get(CURRENT_REMOTE_USER);
    Integer curHttpSession = (Integer) ThreadLocalManager.get(CURRENT_HTTP_SESSION);
    String curContext = (String) ThreadLocalManager.get(CURRENT_CONTEXT);
    ServletRequest curRequest = (ServletRequest) ThreadLocalManager.get(CURRENT_HTTP_REQUEST);
    ServletResponse curResponse = (ServletResponse) ThreadLocalManager.get(CURRENT_HTTP_RESPONSE);
    boolean cleared = false;

    // keep track of temp files with this request that need to be deleted on the way out
    List<FileItem> tempFiles = new ArrayList<FileItem>();

    try {
        ThreadLocalManager.set(CURRENT_REMOTE_USER, Boolean.valueOf(m_sakaiRemoteUser));
        ThreadLocalManager.set(CURRENT_HTTP_SESSION, Integer.valueOf(m_sakaiHttpSession));
        ThreadLocalManager.set(CURRENT_CONTEXT, m_contextId);

        // make the servlet context available
        ThreadLocalManager.set(CURRENT_SERVLET_CONTEXT, m_servletContext);

        // we are expecting HTTP stuff
        if (!((requestObj instanceof HttpServletRequest) && (responseObj instanceof HttpServletResponse))) {
            // if not, just pass it through
            chain.doFilter(requestObj, responseObj);
            return;
        }

        HttpServletRequest req = (HttpServletRequest) requestObj;
        HttpServletResponse resp = (HttpServletResponse) responseObj;

        // knl-640
        // The AppDomain should reject:
        // 1) all GET URL's starting with contentPaths
        //
        // The FileDomain should only accept:
        // 1) any URL's in loginPath. We have to accept POST methods here
        //    as well so folks can log in on this node.
        // 2) any GET URL's from contentPaths (POST's any other methods not
        //    allowed.
        if (useContentHostingDomain) {
            String requestURI = req.getRequestURI();
            if (req.getQueryString() != null)
                requestURI += "?" + req.getQueryString();
            if (startsWithAny(requestURI, contentPaths) && "GET".equalsIgnoreCase(req.getMethod())) {
                if (!req.getServerName().equals(chsDomain) && !(startsWithAny(requestURI, contentExceptions))) {
                    resp.sendRedirect(chsUrl + requestURI);
                    return;
                }
            } else {
                if (req.getServerName().equals(chsDomain)
                        && !(startsWithAny(requestURI, contentPaths)
                                && !"GET".equalsIgnoreCase(req.getMethod()))
                        && !(startsWithAny(requestURI, loginPaths))) {
                    resp.sendRedirect(appUrl + requestURI);
                    return;
                }
            }
        }

        // check on file uploads and character encoding BEFORE checking if
        // this request has already been filtered, as the character encoding
        // and file upload handling are configurable at the tool level.
        // so the 2nd invokation of the RequestFilter (at the tool level)
        // may actually cause character encoding and file upload parsing
        // to happen.

        // handle character encoding
        handleCharacterEncoding(req, resp);

        // handle file uploads
        req = handleFileUpload(req, resp, tempFiles);

        // if we have already filtered this request, pass it on
        if (req.getAttribute(ATTR_FILTERED) != null) {
            // set the request and response for access via the thread local
            ThreadLocalManager.set(CURRENT_HTTP_REQUEST, req);
            ThreadLocalManager.set(CURRENT_HTTP_RESPONSE, resp);

            chain.doFilter(req, resp);
        }

        // filter the request
        else {
            if (M_log.isDebugEnabled()) {
                sb = new StringBuffer("http-request: ");
                sb.append(req.getMethod());
                sb.append(" ");
                sb.append(req.getRequestURL());
                if (req.getQueryString() != null) {
                    sb.append("?");
                    sb.append(req.getQueryString());
                }
                M_log.debug(sb);
            }

            try {
                // mark the request as filtered to avoid re-filtering it later in the request processing
                req.setAttribute(ATTR_FILTERED, ATTR_FILTERED);

                // some useful info
                ThreadLocalManager.set(ServerConfigurationService.CURRENT_SERVER_URL, serverUrl(req));

                // make sure we have a session
                Session s = assureSession(req, resp);

                // pre-process request
                req = preProcessRequest(s, req);

                // detect a tool placement and set the current tool session
                detectToolPlacement(s, req);

                // pre-process response
                resp = preProcessResponse(s, req, resp);

                // set the request and response for access via the thread local
                ThreadLocalManager.set(CURRENT_HTTP_REQUEST, req);
                ThreadLocalManager.set(CURRENT_HTTP_RESPONSE, resp);

                // set the portal into thread local
                if (m_contextId != null && m_contextId.length() > 0) {
                    ThreadLocalManager.set(ServerConfigurationService.CURRENT_PORTAL_PATH, "/" + m_contextId);
                }

                // Only synchronize on session for Terracotta. See KNL-218, KNL-75.
                if (TERRACOTTA_CLUSTER) {
                    synchronized (s) {
                        // Pass control on to the next filter or the servlet
                        chain.doFilter(req, resp);

                        // post-process response
                        postProcessResponse(s, req, resp);
                    }
                } else {
                    // Pass control on to the next filter or the servlet
                    chain.doFilter(req, resp);

                    // post-process response
                    postProcessResponse(s, req, resp);
                }

                // Output client cookie if requested to do so
                if (s != null && req.getAttribute(ATTR_SET_COOKIE) != null) {

                    // check for existing cookie
                    String suffix = getCookieSuffix();
                    Cookie c = findCookie(req, cookieName, suffix);

                    // the cookie value we need to use
                    String sessionId = s.getId() + DOT + suffix;

                    // set the cookie if necessary
                    if ((c == null) || (!c.getValue().equals(sessionId))) {
                        c = new Cookie(cookieName, sessionId);
                        c.setPath("/");
                        c.setMaxAge(-1);
                        if (cookieDomain != null) {
                            c.setDomain(cookieDomain);
                        }
                        if (req.isSecure() == true) {
                            c.setSecure(true);
                        }
                        addCookie(resp, c);
                    }
                }

            } catch (ClosingException se) {
                closingRedirect(req, resp);
            } catch (RuntimeException t) {
                M_log.error("", t);
                throw t;
            } catch (IOException ioe) {
                M_log.error("", ioe);
                throw ioe;
            } catch (ServletException se) {
                M_log.error(se.getMessage(), se);
                throw se;
            } finally {
                // clear any bound current values
                ThreadLocalManager.clear();
                cleared = true;
            }
        }

    } finally {
        if (!cleared) {
            // restore the "current" bindings
            ThreadLocalManager.set(CURRENT_REMOTE_USER, curRemoteUser);
            ThreadLocalManager.set(CURRENT_HTTP_SESSION, curHttpSession);
            ThreadLocalManager.set(CURRENT_CONTEXT, curContext);
            ThreadLocalManager.set(CURRENT_HTTP_REQUEST, curRequest);
            ThreadLocalManager.set(CURRENT_HTTP_RESPONSE, curResponse);
        }

        // delete any temp files
        deleteTempFiles(tempFiles);

        if (M_log.isDebugEnabled() && sb != null) {
            long elapsedTime = System.currentTimeMillis() - startTime;
            M_log.debug("request timing (ms): " + elapsedTime + " for " + sb);
        }
    }
}

From source file:org.ireland.jnetty.http.HttpServletRequestImpl.java

/**
 * Extracte cookies./*  w w w .j a  v a 2 s. com*/
 */
protected void extracteCookie() {
    _cookiesExtracted = true;

    // Decode the cookie.
    String cookieString = headers.get(HttpHeaders.Names.COOKIE);
    if (cookieString != null) {
        Set<io.netty.handler.codec.http.Cookie> _cookies = CookieDecoder.decode(cookieString);

        this.cookies = new Cookie[_cookies.size()];

        int i = 0;

        // Convent netty's Cookie to Servlet's Cookie
        for (io.netty.handler.codec.http.Cookie c : _cookies) {
            Cookie cookie = new Cookie(c.getName(), c.getValue());

            cookie.setComment(c.getComment());

            if (c.getDomain() != null)
                cookie.setDomain(c.getDomain());

            cookie.setHttpOnly(c.isHttpOnly());
            cookie.setMaxAge((int) c.getMaxAge());
            cookie.setPath(c.getPath());
            cookie.setSecure(c.isSecure());
            cookie.setVersion(c.getVersion());

            this.cookies[i] = cookie;
            i++;
        }
    }
}

From source file:org.apache.coyote.tomcat5.CoyoteRequest.java

/**
 * Configures the given JSESSIONID cookie.
 *
 * @param cookie The JSESSIONID cookie to be configured
 *//*from w  w  w  .  j ava2 s  .c  om*/
protected void configureSessionCookie(Cookie cookie) {
    cookie.setMaxAge(-1);
    String contextPath = null;
    if (getContext() != null) {
        contextPath = getContext().getPath();
    }
    if ((contextPath != null) && (contextPath.length() > 0)) {
        cookie.setPath(contextPath);
    } else {
        cookie.setPath("/");
    }
    if (isSecure()) {
        cookie.setSecure(true);
    }
}

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

public void invoke(Object context, ValveContext valveContext) throws PipelineException {
    if (!isEnabled()) {
        valveContext.invokeNext(context);
        return;/*from  w  w  w .  j  a  v  a  2  s .  co  m*/
    }

    AuthValveContext authContext = (AuthValveContext) context;
    JCRUserNode jahiaUser = null;
    // now lets look for a cookie in case we are using cookie-based
    // authentication.
    Cookie[] cookies = cookieAuthConfig.isActivated() ? authContext.getRequest().getCookies() : null;
    if (cookies == null) {
        // no cookies at all sent by the client, let's go to the next
        // valve.
        valveContext.invokeNext(context);
        return;
    }
    // we first need to find the authentication cookie in the list.
    Cookie authCookie = null;
    for (Cookie curCookie : cookies) {
        if (cookieAuthConfig.getCookieName().equals(curCookie.getName())) {
            // found it.
            authCookie = curCookie;
            break;
        }
    }
    if (authCookie != null) {
        // now we need to look in the database to see if we have a
        // user that has the corresponding key.
        Properties searchCriterias = new Properties();
        String userPropertyName = cookieAuthConfig.getUserPropertyName();
        String value = authCookie.getValue();
        String realm = null;
        if (value.contains(":")) {
            realm = StringUtils.substringAfter(value, ":");
            value = StringUtils.substringBefore(value, ":");
        }
        if (value.equals("deleted")) {
            valveContext.invokeNext(context);
            return;
        }
        searchCriterias.setProperty(userPropertyName, value);
        Set<JCRUserNode> foundUsers = null;
        try {
            foundUsers = ServicesRegistry.getInstance().getJahiaUserManagerService().searchUsers(
                    searchCriterias, realm, null,
                    JCRSessionFactory.getInstance().getCurrentSystemSession("live", null, null));
            if (foundUsers.size() == 1) {
                jahiaUser = foundUsers.iterator().next();
                if (jahiaUser.isAccountLocked()) {
                    jahiaUser = null;
                } else {
                    HttpSession session = authContext.getRequest().getSession(false);
                    if (session != null) {
                        session.setAttribute(Constants.SESSION_USER, jahiaUser.getJahiaUser());
                    }

                    if (cookieAuthConfig.isRenewalActivated()) {
                        createAndSendCookie(authContext, jahiaUser, cookieAuthConfig);
                    }
                }
            } else {
                authCookie = new Cookie(cookieAuthConfig.getCookieName(), "deleted");
                authCookie.setPath(StringUtils.isNotEmpty(authContext.getRequest().getContextPath())
                        ? authContext.getRequest().getContextPath()
                        : "/");
                authCookie.setMaxAge(0);
                authCookie.setHttpOnly(cookieAuthConfig.isHttpOnly());
                authCookie.setSecure(cookieAuthConfig.isSecure());
                authContext.getResponse().addCookie(authCookie);
            }
        } catch (RepositoryException e) {
            logger.error("Error while searching for users", e);
        }
    }
    if (jahiaUser == null) {
        valveContext.invokeNext(context);
    } else {
        if (authContext.getRequest().getSession(false) != null) {
            authContext.getRequest().getSession().invalidate();
        }
        authContext.getSessionFactory().setCurrentUser(jahiaUser.getJahiaUser());

        try {
            jahiaUser.setProperty(Constants.JCR_LASTLOGINDATE, String.valueOf(System.currentTimeMillis()));
            jahiaUser.save();
        } catch (RepositoryException e) {
            logger.error(e.getMessage(), e);
        }
    }
}

From source file:org.sakaiproject.util.RequestFilter.java

/**
 * Make sure we have a Sakai session./*from  www .j ava2 s  .com*/
 *
 * @param req
 *        The request object.
 * @param res
 *        The response object.
 * @return The Sakai Session object.
 */
protected Session assureSession(HttpServletRequest req, HttpServletResponse res) {
    Session s = null;
    String sessionId = null;
    boolean allowSetCookieEarly = true;
    Cookie c = null;

    // automatic, i.e. not from user activity, request?
    boolean auto = req.getParameter(PARAM_AUTO) != null;

    // session id provided in a request parameter?
    boolean reqsession = m_sessionParamAllow && req.getParameter(ATTR_SESSION) != null;

    String suffix = getCookieSuffix();

    // try finding a non-cookie session based on the remote user / principal
    // Note: use principal instead of remote user to avoid any possible confusion with the remote user set by single-signon
    // auth.
    // Principal is set by our Dav interface, which this is designed to cover. -ggolden

    Principal principal = req.getUserPrincipal();

    if (m_checkPrincipal && (principal != null) && (principal.getName() != null)) {
        // set our session id to the remote user id
        sessionId = SessionManager.makeSessionId(req, principal);

        // don't supply this cookie to the client
        allowSetCookieEarly = false;

        // find the session
        s = SessionManager.getSession(sessionId);

        // if not found, make a session for this user
        if (s == null) {
            s = SessionManager.startSession(sessionId);
        }

        // Make these sessions expire after 10 minutes
        s.setMaxInactiveInterval(10 * 60);
    }

    // if no principal, check request parameter and cookie
    if (sessionId == null || s == null) {
        if (m_sessionParamAllow) {
            sessionId = req.getParameter(ATTR_SESSION);
        }

        // find our session id from our cookie
        c = findCookie(req, cookieName, suffix);

        if (sessionId == null && c != null) {
            // get our session id
            sessionId = c.getValue();
        }

        if (sessionId != null) {
            // remove the server id suffix
            final int dotPosition = sessionId.indexOf(DOT);
            if (dotPosition > -1) {
                sessionId = sessionId.substring(0, dotPosition);
            }
            if (M_log.isDebugEnabled()) {
                M_log.debug("assureSession found sessionId in cookie: " + sessionId);
            }

            // find the session
            s = SessionManager.getSession(sessionId);
        }

        // ignore the session id provided in a request parameter
        // if the session is not authenticated
        if (reqsession && s != null && s.getUserId() == null) {
            s = null;
        }
    }

    // if found and not automatic, mark it as active
    if ((s != null) && (!auto)) {
        synchronized (s) {
            s.setActive();
        }
    }
    if (s == null && sessionId != null) {
        // check to see if this session has already been built.  If not, rebuild
        RebuildBreakdownService rebuildBreakdownService = (RebuildBreakdownService) ComponentManager
                .get(RebuildBreakdownService.class);
        if (rebuildBreakdownService != null) {
            s = SessionManager.startSession(sessionId);
            if (!rebuildBreakdownService.rebuildSession(s)) {
                s.invalidate();
                s = null;
            }
        }
    }

    // if missing, make one
    if (s == null) {
        s = SessionManager.startSession();

        // if we have a cookie, but didn't find the session and are creating a new one, mark this
        if (c != null) {
            ThreadLocalManager.set(SessionManager.CURRENT_INVALID_SESSION,
                    SessionManager.CURRENT_INVALID_SESSION);
        }
    }

    // put the session in the request attribute
    req.setAttribute(ATTR_SESSION, s);

    // set this as the current session
    SessionManager.setCurrentSession(s);

    // Now that we know the session exists, regardless of whether it's new or not, lets see if there
    // is a UsageSession.  If so, we want to check it's serverId
    UsageSession us = null;
    // FIXME synchronizing on a changing value is a bad practice plus it is possible for s to be null according to the visible code -AZ
    synchronized (s) {
        us = (UsageSession) s.getAttribute(UsageSessionService.USAGE_SESSION_KEY);
        if (us != null) {
            // check the server instance id
            ServerConfigurationService configService = org.sakaiproject.component.cover.ServerConfigurationService
                    .getInstance();
            String serverInstanceId = configService.getServerIdInstance();
            if ((serverInstanceId != null) && (!serverInstanceId.equals(us.getServer()))) {
                // Log that the UsageSession server value is changing
                M_log.info("UsageSession: Server change detected: Old Server=" + us.getServer()
                        + "    New Server=" + serverInstanceId);
                // set the new UsageSession server value
                us.setServer(serverInstanceId);
            }
        }
    }

    // if we had a cookie and we have no session, clear the cookie TODO: detect closed session in the request
    if ((s == null) && (c != null)) {
        // remove the cookie
        c = new Cookie(cookieName, "");
        c.setPath("/");
        c.setMaxAge(0);
        if (cookieDomain != null) {
            c.setDomain(cookieDomain);
        }
        addCookie(res, c);
    }

    // if we have a session and had no cookie,
    // or the cookie was to another session id, set the cookie
    if ((s != null) && allowSetCookieEarly) {
        // the cookie value we need to use
        sessionId = s.getId() + DOT + suffix;

        if ((c == null) || (!c.getValue().equals(sessionId))) {
            // set the cookie
            c = new Cookie(cookieName, sessionId);
            c.setPath("/");
            c.setMaxAge(-1);
            if (cookieDomain != null) {
                c.setDomain(cookieDomain);
            }
            if (req.isSecure() == true) {
                c.setSecure(true);
            }
            addCookie(res, c);
        }
    }

    return s;
}