Example usage for javax.servlet.http Cookie setPath

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

Introduction

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

Prototype

public void setPath(String uri) 

Source Link

Document

Specifies a path for the cookie to which the client should return the cookie.

Usage

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);//from   ww  w.j  av a  2s.  co m
        } else if ("Path".equalsIgnoreCase(directive)) {
            cookie.setPath(_val);
        }

    }

    return cookie;
}

From source file:com.jfinal.core.Controller.java

/**
 * Set Cookie to response./*from   ww w. j  a  va2 s  .  co  m*/
 * @param name cookie name
 * @param value cookie value
 * @param maxAgeInSeconds -1: clear cookie when close browser. 0: clear cookie immediately.  n>0 : max age in n seconds.
 * @param path see Cookie.setPath(String)
 * @param domain the domain name within which this cookie is visible; form is according to RFC 2109
 */
public Controller setCookie(String name, String value, int maxAgeInSeconds, String path, String domain) {
    Cookie cookie = new Cookie(name, value);
    if (domain != null)
        cookie.setDomain(domain);
    cookie.setMaxAge(maxAgeInSeconds);
    cookie.setPath(path);
    response.addCookie(cookie);
    return this;
}

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.j  av  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;
}

From source file:MyServlet.java

public void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, java.io.IOException {

    Cookie cookie = null;
    //Get an array of Cookies associated with this domain
    Cookie[] cookies = request.getCookies();
    boolean newCookie = false;

    //Get the 'mycookie' Cookie if it exists
    if (cookies != null) {
        for (int i = 0; i < cookies.length; i++) {
            if (cookies[i].getName().equals("mycookie")) {
                cookie = cookies[i];// w  ww  . j av a2s . c o m
            }
        } //end for
    } //end if

    if (cookie == null) {
        newCookie = true;
        //Get the cookie's Max-Age from a context-param element
        //If the 'cookie-age' param is not set properly
        //then set the cookie to a default of -1, 'never expires'
        int maxAge;
        try {
            maxAge = new Integer(getServletContext().getInitParameter("cookie-age")).intValue();
        } catch (Exception e) {
            maxAge = -1;
        }

        //Create the Cookie object

        cookie = new Cookie("mycookie", "" + getNextCookieValue());
        cookie.setPath(request.getContextPath());
        cookie.setMaxAge(maxAge);
        response.addCookie(cookie);

    } //end if
      // get some info about the cookie
    response.setContentType("text/html");
    java.io.PrintWriter out = response.getWriter();

    out.println("<html>");
    out.println("<head>");
    out.println("<title>Cookie info</title>");
    out.println("</head>");
    out.println("<body>");

    out.println("<h2> Information about the cookie named \"mycookie\"</h2>");

    out.println("Cookie value: " + cookie.getValue() + "<br>");
    if (newCookie) {
        out.println("Cookie Max-Age: " + cookie.getMaxAge() + "<br>");
        out.println("Cookie Path: " + cookie.getPath() + "<br>");
    }

    out.println("</body>");
    out.println("</html>");

    out.close();
}

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

@Override
public void writeSession(UrlHolder holder, TremoloHttpSession session, HttpServletRequest request,
        HttpServletResponse response) throws IOException {
    /*/*w  w  w. j a  v  a 2  s . c o  m*/
     * Enumeration enumer = session.getAttributeNames(); while
     * (enumer.hasMoreElements()) { String name = (String)
     * enumer.nextElement(); String value =
     * session.getAttribute(name).toString(); logger.debug(name + "='" +
     * value + "'"); }
     */

    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    GZIPOutputStream gzip = new GZIPOutputStream(bos);
    ObjectOutputStream oos = new ObjectOutputStream(gzip);
    oos.writeObject(session);
    oos.flush();
    oos.close();

    byte[] encSession = new byte[0];

    try {
        Cipher cipher = Cipher.getInstance("AES");
        cipher.init(Cipher.ENCRYPT_MODE,
                holder.getConfig().getSecretKey(holder.getApp().getCookieConfig().getKeyAlias()));
        encSession = cipher.doFinal(bos.toByteArray());
    } catch (Exception e) {
        e.printStackTrace();
    }
    Cookie sessionCookie;
    sessionCookie = new Cookie(holder.getApp().getCookieConfig().getSessionCookieName(),
            new String(Base64.encodeBase64(encSession)));

    // logger.debug("session size : " +
    // org.apache.directory.shared.ldap.util.Base64.encode(encSession).length);

    String domain = ProxyTools.getInstance().getCookieDomain(holder.getApp().getCookieConfig(), request);
    if (domain != null) {
        sessionCookie.setDomain(domain);
    }
    sessionCookie.setPath("/");
    sessionCookie.setSecure(false);
    sessionCookie.setMaxAge(-1);
    response.addCookie(sessionCookie);
}

From source file:org.nuxeo.ecm.platform.ui.web.auth.NuxeoAuthenticationFilter.java

protected boolean handleLogout(ServletRequest request, ServletResponse response,
        CachableUserIdentificationInfo cachedUserInfo) throws ServletException {
    logLogout(cachedUserInfo.getUserInfo());

    // invalidate Session !
    service.invalidateSession(request);/*  ww  w  .j  ava2s .com*/

    request.setAttribute(DISABLE_REDIRECT_REQUEST_KEY, Boolean.TRUE);
    Map<String, String> parameters = new HashMap<String, String>();
    String securityError = request.getParameter(SECURITY_ERROR);
    if (securityError != null) {
        parameters.put(SECURITY_ERROR, securityError);
    }
    if (cachedUserInfo.getPrincipal().getName().equals(getAnonymousId())) {
        parameters.put(FORCE_ANONYMOUS_LOGIN, "true");
    }
    String requestedUrl = request.getParameter(REQUESTED_URL);
    if (requestedUrl != null) {
        parameters.put(REQUESTED_URL, requestedUrl);
    }
    // Reset JSESSIONID Cookie
    HttpServletResponse httpResponse = (HttpServletResponse) response;
    Cookie cookie = new Cookie("JSESSIONID", null);
    cookie.setMaxAge(0);
    cookie.setPath("/");
    httpResponse.addCookie(cookie);

    String pluginName = cachedUserInfo.getUserInfo().getAuthPluginName();
    NuxeoAuthenticationPlugin authPlugin = service.getPlugin(pluginName);
    NuxeoAuthenticationPluginLogoutExtension logoutPlugin = null;

    if (authPlugin instanceof NuxeoAuthenticationPluginLogoutExtension) {
        logoutPlugin = (NuxeoAuthenticationPluginLogoutExtension) authPlugin;
    }

    boolean redirected = false;
    if (logoutPlugin != null) {
        redirected = Boolean.TRUE.equals(
                logoutPlugin.handleLogout((HttpServletRequest) request, (HttpServletResponse) response));
    }
    HttpServletRequest httpRequest = (HttpServletRequest) request;
    if (!redirected && !XMLHTTP_REQUEST_TYPE.equalsIgnoreCase(httpRequest.getHeader("X-Requested-With"))) {
        String baseURL = service.getBaseURL(request);
        try {
            String url = baseURL + LoginScreenHelper.getStartupPagePath();
            url = URIUtils.addParametersToURIQuery(url, parameters);
            ((HttpServletResponse) response).sendRedirect(url);
            redirected = true;
        } catch (IOException e) {
            log.error("Unable to redirect to default start page after logout : " + e.getMessage());
        }
    }

    try {
        cachedUserInfo.getLoginContext().logout();
    } catch (LoginException e) {
        log.error("Unable to logout " + e.getMessage());
    }
    return redirected;
}

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 ww w  .  ja v a  2s .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:org.ireland.jnetty.server.session.SessionManager.java

/**
 * ?JSESSIONID  Cookie/*from w  w w  .  ja v 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:org.openedit.entermedia.modules.AdminModule.java

protected void removeCookie(WebPageRequest inReq) {
    HttpServletResponse res = inReq.getResponse();
    if (res != null) {
        Cookie cookie = new Cookie(createMd5CookieName(inReq, true), "none");
        cookie.setMaxAge(0);/*from   ww  w. ja  va  2  s  .com*/
        cookie.setPath("/"); // http://www.unix.org.ua/orelly/java-ent/servlet/ch07_04.htm
        res.addCookie(cookie);

        cookie = new Cookie(createMd5CookieName(inReq, false), "none");
        cookie.setMaxAge(0);
        cookie.setPath("/"); // http://www.unix.org.ua/orelly/java-ent/servlet/ch07_04.htm
        res.addCookie(cookie);

    }
}

From source file:org.workcast.ssoficlient.service.LoginHandler.java

/**
 * create a cookie to last a year, and set on the response
 *//*ww  w.jav a 2s.co  m*/
public void setTenantCookie(String cookieName, String cookieValue) throws Exception {
    // make a tenant-specific cookie name automatically
    if (aa != null && aa.tenant != null) {
        cookieName = cookieName + URLEncoder.encode(aa.tenant, "UTF-8");
    }
    Cookie c = new Cookie(cookieName, cookieValue);
    c.setMaxAge(30000000); // about 1 year from login
    c.setPath("/");
    response.addCookie(c);
}