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.tremolosecurity.proxy.SessionManagerImpl.java

@Override
public void clearSession(UrlHolder holder, HttpSession sharedSession, HttpServletRequest request,
        HttpServletResponse response) {/*from  w  w w . j  a v a  2s .  c o  m*/
    Cookie sessionCookie;
    sessionCookie = new Cookie(holder.getApp().getCookieConfig().getSessionCookieName(), "LOGGED_OUT");
    String domain = ProxyTools.getInstance().getCookieDomain(holder.getApp().getCookieConfig(), request);
    if (domain != null) {
        sessionCookie.setDomain(domain);
    }
    sessionCookie.setPath("/");
    sessionCookie.setSecure(false);
    sessionCookie.setMaxAge(0);
    response.addCookie(sessionCookie);
    sharedSession.invalidate();

}

From source file:com.fuseim.webapp.ProxyServlet.java

/**
 * Copy cookie from the proxy to the servlet client. Replaces cookie path to local path and
 * renames cookie to avoid collisions.//from w w w.  jav  a2 s. com
 */
protected void copyProxyCookie(HttpServletRequest servletRequest, HttpServletResponse servletResponse,
        String headerValue) {
    List<HttpCookie> cookies = HttpCookie.parse(headerValue);
    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 = doPreserveCookies ? cookie.getName()
                : getCookieNamePrefix(cookie.getName()) + 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);
    }
}

From source file:org.wso2.carbon.identity.sso.saml.servlet.SAMLSSOProviderServlet.java

/**
 * @param sessionId//from   w  ww  .j  a v  a2  s. c  o  m
 * @param req
 * @param resp
 */
private void storeTokenIdCookie(String sessionId, HttpServletRequest req, HttpServletResponse resp,
        String tenantDomain) {
    Cookie samlssoTokenIdCookie = new Cookie("samlssoTokenId", sessionId);
    samlssoTokenIdCookie.setMaxAge(IdPManagementUtil.getIdleSessionTimeOut(tenantDomain) * 60);
    samlssoTokenIdCookie.setSecure(true);
    samlssoTokenIdCookie.setHttpOnly(true);
    resp.addCookie(samlssoTokenIdCookie);
}

From source file:com.jolira.testing.CachingRESTProxy.java

private Cookie parseCookie(final String value) {
    final StringTokenizer izer = new StringTokenizer(value, ";");
    final String _value = izer.nextToken();
    final int pos = _value.indexOf('=');
    final String name = _value.substring(0, pos);
    final String val = _value.substring(pos + 1);
    final Cookie cookie = new Cookie(name, val);

    while (izer.hasMoreTokens()) {
        final String token = izer.nextToken();
        final int _pos = token.indexOf('=');
        final String directive = _pos == -1 ? token : token.substring(0, _pos);
        final String _val = _pos == -1 ? null : token.substring(_pos + 1);

        if ("Domain".equalsIgnoreCase(directive)) {
            cookie.setDomain(_val);
        } else if ("Secure".equalsIgnoreCase(directive)) {
            cookie.setSecure(true);
        } else if ("Path".equalsIgnoreCase(directive)) {
            cookie.setPath(_val);
        }/*from   w w  w  . j a v a  2 s. c o m*/

    }

    return cookie;
}

From source file:com.vmware.identity.samlservice.LogoutState.java

private void removeSessionCookie(String cookieName, HttpServletResponse response) {
    Validate.notNull(response);/*from   ww  w .j a v a2 s .  c o  m*/
    if (cookieName == null || cookieName.isEmpty()) {
        log.warn("Cookie name is null or empty. Ignoring.");
        return;
    }
    log.debug("Removing cookie " + cookieName);
    Cookie sessionCookie = new Cookie(cookieName, "");
    sessionCookie.setPath("/");
    sessionCookie.setSecure(true);
    sessionCookie.setHttpOnly(true);
    sessionCookie.setMaxAge(0);
    response.addCookie(sessionCookie);
}

From source file:com.google.gwt.jolokia.server.servlet.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  . j  a  v a  2 s .com*/
protected void copyProxyCookie(HttpServletRequest servletRequest, HttpServletResponse servletResponse,
        Header header) {
    List<HttpCookie> cookies = HttpCookie.parse(header.getValue());
    String path = getServletContext().getServletContextName();
    if (path == null) {
        path = "";
    }
    path += servletRequest.getServletPath();

    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);
    }
}

From source file:com.vmware.identity.samlservice.LogoutState.java

private void addLogoutSessionCookie() throws UnsupportedEncodingException {
    Session session = sessionManager.get(getSessionId());
    if (session != null && session.getAuthnMethod() == AuthnMethod.TLSCLIENT) {
        // set logout session cookie
        String cookieName = Shared.getLogoutCookieName(this.getIdmAccessor().getTenant());
        java.util.Date date = new java.util.Date();
        String timestamp = new Timestamp(date.getTime()).toString();
        String encodedTimestamp = Shared.encodeString(timestamp);
        log.debug("Setting cookie " + cookieName + " value " + encodedTimestamp);
        Cookie sessionCookie = new Cookie(cookieName, encodedTimestamp);
        sessionCookie.setPath("/");
        sessionCookie.setSecure(true);
        sessionCookie.setHttpOnly(true);
        response.addCookie(sessionCookie);
    }//w  w w  .  j  a v a2s  .  c  om
}

From source file:org.rapidcontext.core.web.Request.java

/**
 * Sets the session id cookie in the HTTP response. This method
 * can also be used to clear the session cookie in the web
 * browser (by setting a null value).//ww  w .  jav  a  2s. co m
 *
 * @param sessionId      the session identifier
 * @param expiry         the maximum age of the cookie in seconds
 */
public void setSessionId(String sessionId, int expiry) {
    String value = (sessionId == null) ? "deleted" : sessionId;
    Cookie cookie = new Cookie(SESSION_COOKIE, value);
    cookie.setPath(request.getContextPath() + "/");
    cookie.setSecure(request.isSecure());
    cookie.setMaxAge((sessionId == null) ? 0 : expiry);
    response.addCookie(cookie);
}

From source file:com.versatus.jwebshield.filter.SecurityTokenFilter.java

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

    HttpServletRequest httpReq = (HttpServletRequest) request;
    HttpServletResponse httpRes = (HttpServletResponse) response;
    UrlExclusionList exclList = (UrlExclusionList) request.getServletContext()
            .getAttribute(SecurityConstant.CSRF_CHECK_URL_EXCL_LIST_ATTR_NAME);

    logger.debug("doFilter: request from IP address=" + httpReq.getRemoteAddr());

    if (httpReq.getSession(false) == null) {
        chain.doFilter(request, response);
        return;/*from  w  w w  . j  a va2s.  co  m*/
    }

    logger.debug("doFilter: matching " + httpReq.getRequestURI() + " to exclusions list "
            + exclList.getExclusionMap());

    try {
        if (!exclList.isEmpty() && exclList.isMatch(httpReq.getRequestURI())) {
            chain.doFilter(request, response);
            return;
        }
    } catch (Exception e) {

        logger.error("doFilter", e);
    }

    // Check the user session for the salt cache, if none is present we
    // create one
    Cache<SecurityInfo, SecurityInfo> csrfPreventionSaltCache = (Cache<SecurityInfo, SecurityInfo>) httpReq
            .getSession().getAttribute(SecurityConstant.SALT_CACHE_ATTR_NAME);

    if (csrfPreventionSaltCache == null) {
        if (tokenTimeout == -1) {
            csrfPreventionSaltCache = CacheBuilder.newBuilder().maximumSize(1000).build();
        } else {
            csrfPreventionSaltCache = CacheBuilder.newBuilder().maximumSize(1000)
                    .expireAfterAccess(tokenTimeout, TimeUnit.SECONDS).build();
        }

        httpReq.getSession().setAttribute(SecurityConstant.SALT_CACHE_ATTR_NAME, csrfPreventionSaltCache);

        String nameSalt = RandomStringUtils.random(10, 0, 0, true, true, null, new SecureRandom());
        httpReq.getSession().setAttribute(SecurityConstant.SALT_PARAM_NAME, nameSalt);
    }

    // Generate the salt and store it in the users cache
    String salt = RandomStringUtils.random(20, 0, 0, true, true, null, new SecureRandom());

    String saltNameAttr = (String) httpReq.getSession().getAttribute(SecurityConstant.SALT_PARAM_NAME);
    SecurityInfo si = new SecurityInfo(saltNameAttr, salt);

    if (SecurityTokenFilter.checkReferer) {
        String refHeader = StringUtils.defaultString(httpReq.getHeader("Referer"));
        logger.debug("doFilter: refHeader=" + refHeader);
        if (StringUtils.isNotBlank(refHeader)) {
            try {
                URL refUrl = new URL(refHeader);
                refHeader = refUrl.getHost();
            } catch (MalformedURLException mex) {
                logger.debug("doFilter: parsing referer header failed", mex);
            }
        }

        si.setRefererHost(refHeader);
    }

    logger.debug("doFilter: si=" + si.toString());

    csrfPreventionSaltCache.put(si, si);

    // Add the salt to the current request so it can be used
    // by the page rendered in this request
    httpReq.setAttribute(SecurityConstant.SALT_ATTR_NAME, si);

    // set CSRF cookie
    HttpSession session = httpReq.getSession(false);
    if (session != null && StringUtils.isNotBlank(csrfCookieName)) {

        if (logger.isDebugEnabled()) {
            Cookie[] cookies = httpReq.getCookies();
            // boolean cookiePresent = false;
            for (Cookie c : cookies) {
                String name = c.getName();
                logger.debug("doFilter: cookie domain=" + c.getDomain() + "|name=" + name + "|value="
                        + c.getValue() + "|path=" + c.getPath() + "|maxage=" + c.getMaxAge() + "|httpOnly="
                        + c.isHttpOnly());
                // if (csrfCookieName.equals(name)) {
                // cookiePresent = true;
                // break;
                // }
            }
        }
        // if (!cookiePresent) {
        byte[] hashSalt = new byte[32];
        SecureRandom sr = new SecureRandom();
        sr.nextBytes(hashSalt);

        String csrfHash = RandomStringUtils.random(64, 0, 0, true, true, null, sr);

        Cookie c = new Cookie(csrfCookieName, csrfHash);
        c.setMaxAge(1800);
        c.setSecure(false);
        c.setPath(httpReq.getContextPath());
        c.setHttpOnly(false);
        httpRes.addCookie(c);
        // session.setAttribute(SecurityConstant.CSRFCOOKIE_VALUE_PARAM,
        // hashStr);
        // }
    }

    chain.doFilter(request, response);
}

From source file:com.tremolosecurity.proxy.SessionManagerImpl.java

private HttpSession createSession(ApplicationType app, HttpServletRequest req, HttpServletResponse resp,
        ServletContext ctx, SecretKey encKey) throws Exception {

    byte[] idBytes = new byte[20];
    random.nextBytes(idBytes);//  ww  w .  j  a  v  a2  s.c  o m

    StringBuffer b = new StringBuffer();
    b.append('f').append(Hex.encodeHexString(idBytes));
    String id = b.toString();

    // HttpSession session = req.getSession(true);
    TremoloHttpSession tsession = new TremoloHttpSession(id);
    tsession.setAppName(app.getName());
    tsession.refresh(this.ctx, this);
    tsession.setOpen(false);
    this.anonMech.createSession(tsession, this.anonChainType);

    AuthController actl = (AuthController) tsession.getAttribute(ProxyConstants.AUTH_CTL);

    AuthInfo auInfo = actl.getAuthInfo();
    auInfo.setAuthComplete(true);

    // session.setAttribute(app.getCookieConfig().getSessionCookieName(),
    // tsession);

    tsession.setAttribute(OpenUnisonConstants.TREMOLO_SESSION_ID, id);
    tsession.setMaxInactiveInterval(app.getCookieConfig().getTimeout());

    Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
    cipher.init(Cipher.ENCRYPT_MODE, encKey);

    byte[] encSessionKey = cipher.doFinal(id.getBytes("UTF-8"));
    String base64d = new String(org.bouncycastle.util.encoders.Base64.encode(encSessionKey));

    Token token = new Token();
    token.setEncryptedRequest(base64d);
    token.setIv(new String(org.bouncycastle.util.encoders.Base64.encode(cipher.getIV())));

    Gson gson = new Gson();

    String cookie = gson.toJson(token);

    byte[] btoken = cookie.getBytes("UTF-8");
    String encCookie = new String(org.bouncycastle.util.encoders.Base64.encode(btoken));

    Cookie sessionCookie;

    sessionCookie = new Cookie(app.getCookieConfig().getSessionCookieName(), encCookie);

    // logger.debug("session size : " +
    // org.apache.directory.shared.ldap.util.Base64.encode(encSession).length);
    String domain = ProxyTools.getInstance().getCookieDomain(app.getCookieConfig(), req);
    if (domain != null) {
        sessionCookie.setDomain(domain);
    }
    sessionCookie.setPath("/");
    sessionCookie.setSecure(false);
    sessionCookie.setMaxAge(-1);
    sessionCookie.setSecure(app.getCookieConfig().isSecure());
    sessionCookie.setHttpOnly(app.getCookieConfig().isHttpOnly() != null && app.getCookieConfig().isHttpOnly());
    resp.addCookie(sessionCookie);

    // delete the opensession if it exists
    if (cfg.getCfg().getApplications().getOpenSessionCookieName() != null
            && !cfg.getCfg().getApplications().getOpenSessionCookieName().isEmpty()) {
        Cookie openSessionCookie = new Cookie(cfg.getCfg().getApplications().getOpenSessionCookieName(), id);

        openSessionCookie.setPath("/");
        openSessionCookie.setSecure(cfg.getCfg().getApplications().isOpenSessionSecure());
        openSessionCookie.setHttpOnly(cfg.getCfg().getApplications().isOpenSessionHttpOnly());
        openSessionCookie.setMaxAge(0);
        resp.addCookie(openSessionCookie);
    }

    sessions.put(id, tsession);

    return tsession;
}