Example usage for javax.servlet.http Cookie setHttpOnly

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

Introduction

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

Prototype

public void setHttpOnly(boolean isHttpOnly) 

Source Link

Document

Marks or unmarks this Cookie as <i>HttpOnly</i>.

Usage

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);/*from   w  w  w  . j a  va  2s. c o m*/
        sessionCookie.setHttpOnly(true);
        response.addCookie(sessionCookie);
    }
}

From source file:uk.ac.cam.cl.dtg.segue.api.managers.UserAuthenticationManager.java

/**
 * Create a session and attach it to the request provided.
 * /*  ww  w  . ja  v  a 2  s  .c om*/
 * @param request
 *            to enable access to anonymous user information.
 * @param response
 *            to store the session in our own segue cookie.
 * @param user
 *            account to associate the session with.
 */
private void createSession(final HttpServletRequest request, final HttpServletResponse response,
        final RegisteredUser user) {
    Validate.notNull(response);
    Validate.notNull(user);
    Validate.notNull(user.getId());
    SimpleDateFormat sessionDateFormat = new SimpleDateFormat(DEFAULT_DATE_FORMAT);
    Integer sessionExpiryTimeInSeconds = Integer.parseInt(properties.getProperty(SESSION_EXPIRY_SECONDS));

    String userId = user.getId().toString();
    String hmacKey = properties.getProperty(HMAC_SALT);

    try {
        String currentDate = sessionDateFormat.format(new Date());
        String sessionHMAC = this.calculateSessionHMAC(hmacKey, userId, currentDate);

        Map<String, String> sessionInformation = ImmutableMap.of(SESSION_USER_ID, userId, DATE_SIGNED,
                currentDate, HMAC, sessionHMAC);

        Cookie authCookie = new Cookie(SEGUE_AUTH_COOKIE,
                serializationMapper.writeValueAsString(sessionInformation));
        authCookie.setMaxAge(sessionExpiryTimeInSeconds);
        authCookie.setPath("/");
        authCookie.setHttpOnly(true);

        response.addCookie(authCookie);

    } catch (JsonProcessingException e1) {
        log.error("Unable to save cookie.", e1);
    }
}

From source file:org.ireland.jnetty.server.session.SessionManager.java

/**
 * ?JSESSIONID  Cookie//from ww  w  .j  av  a2 s  .  c o  m
 * @param session
 * @param contextPath
 * @param secure
 * @return
 */
public Cookie getSessionCookie(HttpSessionImpl session, String contextPath, boolean secure) {

    String sessionPath = contextPath;

    sessionPath = (sessionPath == null || sessionPath.length() == 0) ? "/" : sessionPath;

    String id = session.getId();

    Cookie cookie = null;

    cookie = new Cookie(_cookieName, id);

    cookie.setComment(_cookieComment);

    if (_cookieDomain != null)
        cookie.setDomain(_cookieDomain);

    cookie.setHttpOnly(isHttpOnly());
    cookie.setMaxAge((int) _cookieMaxAge);

    cookie.setPath(sessionPath);

    cookie.setSecure(secure);
    cookie.setVersion(_cookieVersion);

    return 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;/*w  w  w  .  j a  va 2 s . 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);//w ww.  ja v a  2  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;
}

From source file:com.jsmartframework.web.manager.BeanHandler.java

private Cookie getAuthenticationCookie(HttpServletRequest request, String name, String value, int age) {
    Cookie cookie = new Cookie(name, value);
    cookie.setHttpOnly(true);/*from  w  w w.  j  a va2s .c om*/
    cookie.setPath("/");
    cookie.setMaxAge(age);
    return cookie;
}

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

/**
 * Extracte cookies./*from w  ww.  ja  va 2  s. co  m*/
 */
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.jahia.params.valves.CookieAuthValveImpl.java

public void invoke(Object context, ValveContext valveContext) throws PipelineException {
    if (!isEnabled()) {
        valveContext.invokeNext(context);
        return;/* w  ww . ja v  a 2  s  .  c o  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);
        }
    }
}