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.redhat.rhn.frontend.servlets.PxtCookieManager.java

/**
 * Creates a new pxt cookie with the specified session id and timeout.
 *
 * @param pxtSessionId The id of the pxt session for which the cookie is being created.
 *
 * @param request The current request.//from ww  w  .  j  ava  2 s.c o  m
 *
 * @param timeout The max age of the cookie in seconds.
 *
 * @return a new pxt cookie.
 */
public Cookie createPxtCookie(Long pxtSessionId, HttpServletRequest request, int timeout) {

    String cookieName = getCookieName(request);
    String cookieValue = pxtSessionId + "x" + SessionManager.generateSessionKey(pxtSessionId.toString());

    Cookie pxtCookie = new Cookie(cookieName, cookieValue);
    // BZ #454876
    // when not using setDomain, default "Host" will be set for the cookie
    // there's no need to use domain and besides that it causes trouble,
    //  when accessing the server within the local network (without FQDN)
    // pxtCookie.setDomain(request.getServerName());
    pxtCookie.setMaxAge(timeout);
    pxtCookie.setPath(DEFAULT_PATH);
    pxtCookie.setSecure(ConfigDefaults.get().isSSLAvailable());

    return pxtCookie;
}

From source file:org.xwiki.contrib.authentication.internal.CookieAuthenticationPersistenceStore.java

/**
 * Set the authentication cookie to the given value and max age.
 * @param value the value to be set./*from ww w. j av a 2 s. c om*/
 * @param maxAge the maximum age of the cookie.
 */
private void setAuthenticationCookie(String value, int maxAge) {
    XWikiContext context = contextProvider.get();

    Cookie cookie = new Cookie(cookiePfx + AUTHENTICATION_COOKIE, value);
    cookie.setMaxAge(maxAge);
    cookie.setPath(cookiePath);
    String cookieDomain = getCookieDomain();
    if (cookieDomain != null) {
        cookie.setDomain(cookieDomain);
    }
    if (context.getRequest().isSecure()) {
        cookie.setSecure(true);
    }
    context.getResponse().addCookie(cookie);
}

From source file:com.nominanuda.web.http.ServletHelper.java

public Cookie servletCookie(HttpCookie c) {
    Cookie _c = new Cookie(c.getName(), c.getValue());
    if (c.getComment() != null) {
        _c.setComment(c.getComment());/*from ww  w .  j a v  a  2 s . c o  m*/
    }
    if (c.getDomain() != null) {
        _c.setDomain(c.getDomain());
    }
    if (c.getPath() != null) {
        _c.setPath(c.getPath());
    }
    _c.setSecure(c.getSecure());
    _c.setVersion(c.getVersion());
    _c.setHttpOnly(c.getDiscard());
    _c.setMaxAge((int) c.getMaxAge());
    return _c;
}

From source file:com.codename1.corsproxy.CORSProxy.java

@Override
protected void copyProxyCookie(HttpServletRequest servletRequest, HttpServletResponse servletResponse,
        Header header) {/*  ww w. ja va  2 s.com*/
    List<HttpCookie> cookies = HttpCookie.parse(header.getValue());
    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.setSecure(false);
        servletCookie.setVersion(cookie.getVersion());
        servletResponse.addCookie(servletCookie);
    }
}

From source file:com.microsoft.azure.oidc.filter.helper.impl.SimpleAuthenticationHelper.java

private String addCookie(final HttpServletRequest httpRequest, final HttpServletResponse httpResponse,
        final String cookieName, final String cookieValue) {
    if (httpRequest == null || httpResponse == null || cookieName == null || cookieValue == null) {
        throw new PreconditionException("Required parameter is null");
    }/* www  .  j  a  v  a 2 s.  co  m*/
    final Cookie cookie = new Cookie(cookieName, "");
    cookie.setValue(cookieValue);
    cookie.setMaxAge(-1);
    cookie.setSecure(true);
    cookie.setDomain(httpRequest.getServerName());
    cookie.setPath("/");
    cookie.setHttpOnly(true);
    httpResponse.addCookie(cookie);
    return cookie.getValue();
}

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

protected Cookie newJossoCookie(String path, String name, String value) throws Exception {
    SSOWebConfiguration cfg = Lookup.getInstance().lookupSSOWebConfiguration();

    Cookie ssoCookie = new Cookie(name, value);
    ssoCookie.setMaxAge(-1);//from www . j  a  va2  s  .c  om

    if (cfg.isSessionTokenSecure()) {
        ssoCookie.setSecure(true);
    }

    ssoCookie.setPath(path);

    return ssoCookie;

    //        if (cfg.getSessionTokenScope() != null) {
    //            ssoCookie.setDomain(cfg.getSessionTokenScope());
    //        }

}

From source file:com.silverpeas.authentication.AuthenticationServlet.java

/**
 * Write session cookie./*from ww  w  .j a va2  s. c o  m*/
 *
 * @return
 */
private void writeSessionCookie(HttpServletResponse response, HttpSession session, boolean secured) {
    Cookie cookie = new Cookie("JSESSIONID", session.getId());
    cookie.setMaxAge(-1);
    cookie.setPath(session.getServletContext().getContextPath());
    cookie.setHttpOnly(true);
    if (secured) {
        cookie.setSecure(secured);
    }
    response.addCookie(cookie);
}

From source file:org.jsecurity.web.attr.CookieAttribute.java

public void removeValue(ServletRequest servletRequest, ServletResponse response) {
    HttpServletRequest request = toHttp(servletRequest);
    Cookie cookie = getCookie(request, getName());
    if (cookie != null) {
        cookie.setMaxAge(0);//  ww  w.  j  a  v  a2 s .c om
        //JSEC-94: Must set the path on the outgoing cookie (some browsers don't retain it from the
        //retrieved cookie?)
        cookie.setPath(getPath() == null ? request.getContextPath() : getPath());
        cookie.setSecure(isSecure());
        toHttp(response).addCookie(cookie);
    }
}

From source file:com.stormcloud.ide.api.filter.UserFilter.java

@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) {

    try {//w  w  w .  j a  va2 s  .com

        HttpServletRequest httpRequest = (HttpServletRequest) request;
        HttpServletResponse httpResponse = (HttpServletResponse) response;

        LOG.info("Filter Request [" + request.getRemoteAddr() + "]");

        MDC.put("api", httpRequest.getRequestURI());

        if (httpRequest.getRequestURI().endsWith("/api/login")) {

            // configure MDC for the remainging trip
            MDC.put("userName", httpRequest.getRemoteUser());

            LOG.debug("Login Request.");

            // it's a login request which succeeded (Basic Auth)
            // so we now need to genereate an authentication token
            // and store it in a cookie we sent back
            // create the cookie with key for consecutive Rest API Calls

            // Get user from db and add to the localthread
            User user = dao.getUser(httpRequest.getRemoteUser());

            if (user == null) {

                LOG.error("User not found.");
                httpResponse.sendError(HttpStatus.FORBIDDEN.value());
                httpResponse.flushBuffer();
                return;
            }

            // update last login
            user.setLastLogin(Calendar.getInstance().getTime());

            dao.save(user);

            RemoteUser.set(user);

            try {

                // set the key cookie
                Cookie keyCookie = new Cookie("stormcloud-key", createKey(user, httpRequest.getRemoteAddr()));

                keyCookie.setMaxAge(60 * 60 * 24); // 1 day

                keyCookie.setPath("/");
                keyCookie.setSecure(true);

                httpResponse.addCookie(keyCookie);

                // set the username cookie
                Cookie userCookie = new Cookie("stormcloud-user", user.getUserName());

                userCookie.setMaxAge(60 * 60 * 24); // 1 day

                userCookie.setPath("/");
                userCookie.setSecure(true);

                httpResponse.addCookie(userCookie);

            } catch (NoSuchAlgorithmException e) {

                LOG.error(e);

                try {

                    // no go
                    httpResponse.sendError(HttpStatus.INTERNAL_SERVER_ERROR.value());

                    httpResponse.flushBuffer();
                    return;

                } catch (IOException ioe) {
                    LOG.error(ioe);
                }
            }

        } else if (httpRequest.getRequestURI().endsWith("/api/user/createAccount")) {

            // intercept and do something with create account
            LOG.debug("Create Account Request.");

        } else {

            LOG.info("API Request.");

            // any other request than a login
            // we need to check the username and received key
            Cookie[] cookies = httpRequest.getCookies();

            String userName = null;
            String key = null;

            if (cookies != null) {

                LOG.info("Found " + cookies.length + " Cookies");

                // loop trough the cookies
                for (int i = 0; i < cookies.length; i++) {

                    if (cookies[i].getName().equals("stormcloud-user")) {

                        LOG.debug("userName = " + cookies[i].getValue());
                        userName = cookies[i].getValue();
                    }

                    if (cookies[i].getName().equals("stormcloud-key")) {

                        LOG.debug("key = " + cookies[i].getValue());
                        key = cookies[i].getValue();
                    }
                }
            }

            if (userName == null || key == null) {

                LOG.info("Required credentials not found.");
                httpResponse.sendError(HttpStatus.FORBIDDEN.value());
                httpResponse.flushBuffer();
                return;

            } else {

                // configure MDC for the remainging trip
                MDC.put("userName", userName);

                // get user
                LOG.debug("Get Persisted User");
                User user = dao.getUser(userName);

                if (user == null) {
                    httpResponse.sendError(HttpStatus.FORBIDDEN.value());
                    httpResponse.flushBuffer();
                    return;
                }

                RemoteUser.set(user);

                try {

                    String matchKey = createKey(user, httpRequest.getRemoteAddr());

                    LOG.info("Validating Key.");

                    if (!matchKey.equals(key)) {

                        LOG.warn("Invalid Key!");
                        httpResponse.sendError(HttpStatus.FORBIDDEN.value());
                        httpResponse.flushBuffer();
                        return;

                    } else {

                        LOG.info("Request Authenticated");
                    }

                } catch (NoSuchAlgorithmException e) {

                    LOG.error(e);

                    try {

                        // no go
                        httpResponse.sendError(HttpStatus.INTERNAL_SERVER_ERROR.value());
                        httpResponse.flushBuffer();
                        return;

                    } catch (IOException ioe) {
                        LOG.error(ioe);
                    }
                }

            }
        }

        chain.doFilter(request, response);

    } catch (IOException e) {
        LOG.error(e);
    } catch (ServletException e) {
        LOG.error(e);
    } finally {

        // clear the logging diagnostics context
        MDC.clear();

        // Remove the user from memoty
        RemoteUser.destroy();
    }
}

From source file:net.ymate.platform.webmvc.util.CookieHelper.java

/**
 * @param key    //  ww w .  j a v  a  2 s  . c  o m
 * @param value  
 * @param maxAge 
 * @return ?Cookie
 */
public CookieHelper setCookie(String key, String value, int maxAge) {
    Cookie _cookie = new Cookie(__owner.getModuleCfg().getCookiePrefix() + key,
            StringUtils.isBlank(value) ? "" : encodeValue(value));
    _cookie.setMaxAge(maxAge);
    _cookie.setPath(__owner.getModuleCfg().getCookiePath());
    if (StringUtils.isNotBlank(__owner.getModuleCfg().getCookieDomain())) {
        _cookie.setDomain(__owner.getModuleCfg().getCookieDomain());
    }
    _cookie.setSecure(WebContext.getRequest().isSecure());
    WebContext.getResponse().addCookie(_cookie);
    return this;
}