Example usage for javax.servlet.http Cookie getPath

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

Introduction

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

Prototype

public String getPath() 

Source Link

Document

Returns the path on the server to which the browser returns this cookie.

Usage

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

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

    // Assume its HTTP
    HttpServletRequest httpReq = (HttpServletRequest) request;

    String reqInfo = "J-WebShield Alert: CSRF attack detected! request URL="
            + httpReq.getRequestURL().toString() + "| from IP address=" + httpReq.getRemoteAddr();

    logger.debug("doFilter: IP address=" + httpReq.getRemoteAddr());
    logger.debug("doFilter: pathInfo=" + httpReq.getPathInfo());
    logger.debug("doFilter: queryString=" + httpReq.getQueryString());
    logger.debug("doFilter: requestURL=" + httpReq.getRequestURL().toString());
    logger.debug("doFilter: method=" + httpReq.getMethod());
    logger.debug("doFilter: Origin=" + httpReq.getHeader("Origin"));
    logger.info("doFilter: Referer=" + httpReq.getHeader("Referer"));
    logger.info("doFilter: " + csrfHeaderName + "=" + httpReq.getHeader(csrfHeaderName));

    UrlExclusionList exclList = (UrlExclusionList) request.getServletContext()
            .getAttribute(SecurityConstant.CSRF_CHECK_URL_EXCL_LIST_ATTR_NAME);
    HttpSession session = httpReq.getSession(false);
    if (session == null) {
        chain.doFilter(request, response);
        return;/*from   ww w  .  j  a v  a2 s.  c o 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 CSRF cookie/header
    boolean csrfHeaderPassed = false;
    String rawCsrfHeaderVal = httpReq.getHeader(csrfHeaderName);
    if (useCsrfToken && StringUtils.isNotBlank(rawCsrfHeaderVal)) {
        String csrfHeader = StringUtils.strip(httpReq.getHeader(csrfHeaderName), "\"");
        logger.debug("doFilter: csrfHeader after decoding" + csrfHeader);
        Cookie[] cookies = httpReq.getCookies();
        for (Cookie c : cookies) {
            String name = c.getName();

            if (StringUtils.isNotBlank(csrfCookieName) && csrfCookieName.equals(name)) {

                logger.debug("doFilter: cookie domain=" + c.getDomain() + "|name=" + name + "|value="
                        + c.getValue() + "|path=" + c.getPath() + "|maxage=" + c.getMaxAge() + "|httpOnly="
                        + c.isHttpOnly());

                logger.debug("doFilter: string comp:" + StringUtils.difference(csrfHeader, c.getValue()));

                if (StringUtils.isNotBlank(csrfHeader) && csrfHeader.equals(c.getValue())) {

                    csrfHeaderPassed = true;
                    logger.info("Header " + csrfHeaderName + " value matches the cookie " + csrfCookieName);
                    break;
                } else {
                    logger.info(
                            "Header " + csrfHeaderName + " value does not match the cookie " + csrfCookieName);
                }
            }

        }
        // String csrfCookieVal = (String) session
        // .getAttribute(SecurityConstant.CSRFCOOKIE_VALUE_PARAM);
        // if (csrfCookieVal != null && csrfCookieVal.equals(csrfHeader)) {
        // // chain.doFilter(request, response);
        // // return;
        // csrfHeaderPassed = true;
        // } else {
        // // logger.info(reqInfo);
        // // sendSecurityReject(response);
        // }
    }

    if (useCsrfToken && csrfHeaderPassed) {
        chain.doFilter(request, response);
        return;
    }

    // Validate that the salt is in the cache
    Cache<SecurityInfo, SecurityInfo> csrfPreventionSaltCache = (Cache<SecurityInfo, SecurityInfo>) httpReq
            .getSession().getAttribute(SecurityConstant.SALT_CACHE_ATTR_NAME);

    if (csrfPreventionSaltCache != null) {
        // Get the salt sent with the request
        String saltName = (String) httpReq.getSession().getAttribute(SecurityConstant.SALT_PARAM_NAME);

        logger.debug("doFilter: csrf saltName=" + saltName);

        if (saltName != null) {

            String salt = httpReq.getParameter(saltName);

            logger.debug("doFilter: csrf salt=" + salt);

            if (salt != null) {

                SecurityInfo si = new SecurityInfo(saltName, salt);

                logger.debug("doFilter: csrf token=" + csrfPreventionSaltCache.getIfPresent(si));

                SecurityInfo cachedSi = csrfPreventionSaltCache.getIfPresent(si);
                if (cachedSi != null) {
                    // csrfPreventionSaltCache.invalidate(si);
                    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);
                            }
                        }
                        if (!cachedSi.getRefererHost().isEmpty()
                                && !refHeader.equalsIgnoreCase(cachedSi.getRefererHost())) {
                            logger.info("Potential CSRF detected - Referer host does not match orignal! "
                                    + refHeader + " != " + cachedSi.getRefererHost());
                            sendSecurityReject(response);
                        }
                    }

                    chain.doFilter(request, response);
                } else {
                    logger.info(reqInfo);
                    sendSecurityReject(response);
                }
            } else if (httpMethodMatch(httpReq.getMethod())) {
                // let flow through
                chain.doFilter(request, response);
            } else {
                logger.info(reqInfo);
                sendSecurityReject(response);
            }
        }
    } else {
        chain.doFilter(request, response);
    }

}

From source file:com.xpn.xwiki.stats.impl.StatsUtil.java

/**
 * Create a new visit cookie and return it.
 * //from w  w w .  jav  a 2 s .com
 * @param context the XWiki context.
 * @return the newly created cookie.
 * @since 1.4M1
 */
protected static Cookie addCookie(XWikiContext context) {
    Cookie cookie = new Cookie(COOKPROP_VISITID, RandomStringUtils.randomAlphanumeric(32).toUpperCase());
    cookie.setPath("/");

    int time = (int) (getCookieExpirationDate().getTime() - (new Date()).getTime()) / 1000;
    cookie.setMaxAge(time);

    String cookieDomain = null;
    getCookieDomains(context);
    if (cookieDomains != null) {
        String servername = context.getRequest().getServerName();
        for (int i = 0; i < cookieDomains.length; i++) {
            if (servername.indexOf(cookieDomains[i]) != -1) {
                cookieDomain = cookieDomains[i];
                break;
            }
        }
    }

    if (cookieDomain != null) {
        cookie.setDomain(cookieDomain);
    }

    if (LOGGER.isDebugEnabled()) {
        LOGGER.debug("Setting cookie " + cookie.getValue() + " for name " + cookie.getName() + " with domain "
                + cookie.getDomain() + " and path " + cookie.getPath() + " and maxage " + cookie.getMaxAge());
    }

    context.getResponse().addCookie(cookie);

    return cookie;
}

From source file:com.xpn.xwiki.user.impl.xwiki.MyPersistentLoginManager.java

/**
 * Adds a cookie to the response.//ww  w. j  a  va 2 s . c  o  m
 * 
 * @param response The servlet response.
 * @param cookie The cookie to be sent.
 */
private void addCookie(HttpServletResponse response, Cookie cookie) {
    if (LOGGER.isDebugEnabled()) {
        LOGGER.debug("Adding cookie: " + cookie.getDomain() + cookie.getPath() + " " + cookie.getName() + "="
                + cookie.getValue());
    }
    // We don't use the container's response.addCookie, since the HttpOnly cookie flag was introduced only recently
    // in the servlet specification, and we're still using the older 2.4 specification as a minimal requirement for
    // compatibility with as many containers as possible. Instead, we write the cookie manually as a HTTP header.
    StringBuilder cookieValue = new StringBuilder(150);
    cookieValue.append(cookie.getName() + "=");
    if (StringUtils.isNotEmpty(cookie.getValue())) {
        cookieValue.append("\"" + cookie.getValue() + "\"");
    }
    cookieValue.append("; Version=1");
    if (cookie.getMaxAge() >= 0) {
        cookieValue.append("; Max-Age=" + cookie.getMaxAge());
        // IE is such a pain, it doesn't understand the modern, safer Max-Age
        cookieValue.append("; Expires=");
        if (cookie.getMaxAge() == 0) {
            cookieValue.append(COOKIE_EXPIRE_NOW);
        } else {
            cookieValue.append(COOKIE_EXPIRE_FORMAT
                    .format(new Date(System.currentTimeMillis() + cookie.getMaxAge() * 1000L)));
        }
    }
    if (StringUtils.isNotEmpty(cookie.getDomain())) {
        // IE needs toLowerCase for the domain name
        cookieValue.append("; Domain=" + cookie.getDomain().toLowerCase());
    }
    if (StringUtils.isNotEmpty(cookie.getPath())) {
        cookieValue.append("; Path=" + cookie.getPath());
    }
    // Protect cookies from being used from JavaScript, see http://www.owasp.org/index.php/HttpOnly
    cookieValue.append("; HttpOnly");

    // Session cookies should be discarded.
    // FIXME Safari 5 can't handle properly "Discard", as it really discards all the response header data after the
    // first "Discard" encountered, so it will only see the first such cookie. Disabled for the moment until Safari
    // gets fixed, or a better idea comes to mind.
    // Since we don't set a Max-Age, the rfc2109 behavior will kick in, and recognize this as a session cookie.
    // if (cookie.getMaxAge() < 0) {
    // cookieValue.append("; Discard");
    // }
    response.addHeader("Set-Cookie", cookieValue.toString());
}

From source file:fr.smile.liferay.EsigatePortlet.java

/**
 * Transform request to IncominqRequest// w  ww  .j  a  v a2s.  c  o  m
 *
 * @param request
 * @param method
 * @return an incoming request
 * @throws IOException
 */
public IncomingRequest create(PortletRequest request, String method) throws IOException {

    HttpServletRequest httpServletRequest = PortalUtil
            .getOriginalServletRequest(PortalUtil.getHttpServletRequest(request));

    StringBuilder uri = new StringBuilder(HTTP_BASE_INCOMING_URL);

    StringBuilder query = new StringBuilder();
    Enumeration<String> parameters = request.getParameterNames();
    String sep = "";
    while (parameters.hasMoreElements()) {
        String name = parameters.nextElement();
        String[] values = request.getParameterValues(name);
        if (!name.equals(ACTION_PARAMETER)) {
            for (String value : values) {
                query.append(sep);
                query.append(name).append("=").append(URLEncoder.encode(value, "UTF-8"));
                sep = "&";
            }
        }
    }

    ProtocolVersion protocolVersion = HttpVersion.HTTP_1_1.forVersion(1, 0);

    if (method.equals("GET")) {
        if (!query.toString().isEmpty()) {
            if (!uri.toString().contains("?")) {
                uri.append("?");
            } else {
                uri.append("&");
            }
            uri.append(query);
        }
    }
    if (LOG.isDebugEnabled()) {
        LOG.debug("Creating Incoming request with method " + method + ", URI " + uri + ", protocoleVersion "
                + protocolVersion);
    }
    IncomingRequest.Builder builder = IncomingRequest
            .builder(new BasicRequestLine(method, uri.toString(), protocolVersion));

    if (method.equals("POST")) {
        // create entity
        InputStream inputStream = IOUtils.toInputStream(query.toString());

        if (inputStream != null) {
            // Copy entity-related headers
            InputStreamEntity entity = new InputStreamEntity(inputStream, query.length());
            String contentTypeHeader = httpServletRequest.getContentType();
            if (contentTypeHeader != null) {
                entity.setContentType(contentTypeHeader);
            }
            String contentEncodingHeader = httpServletRequest.getCharacterEncoding();
            if (contentEncodingHeader != null) {
                entity.setContentEncoding(contentEncodingHeader);
            }
            builder.setEntity(entity);
        }
    }

    HttpServletRequestContext context = new HttpServletRequestContext(httpServletRequest, null, null);
    builder.setContext(context);
    builder.setRemoteAddr(httpServletRequest.getRemoteAddr());
    builder.setRemoteUser(request.getRemoteUser());
    HttpSession session = httpServletRequest.getSession(false);
    if (session != null) {
        builder.setSessionId(session.getId());
    }
    builder.setUserPrincipal(request.getUserPrincipal());
    // Copy cookies
    javax.servlet.http.Cookie[] src = request.getCookies();

    if (src != null) {
        LOG.debug("Copying " + src.length + " cookie(s) to response.");
        for (int i = 0; i < src.length; i++) {
            javax.servlet.http.Cookie c = src[i];
            BasicClientCookie dest = new BasicClientCookie(c.getName(), c.getValue());
            dest.setSecure(c.getSecure());
            dest.setDomain(c.getDomain());
            dest.setPath(c.getPath());
            dest.setComment(c.getComment());
            dest.setVersion(c.getVersion());
            builder.addCookie(dest);
        }
    }

    builder.setSession(new HttpServletSession(httpServletRequest));

    IncomingRequest incomingRequest = builder.build();
    return incomingRequest;

}

From source file:com.google.gsa.valve.modules.ldap.LDAPUniqueCreds.java

/**
 * Sets the LDAP authentication cookie//ww w  .  j a  va 2s. c om
 * 
 * @return the LDAP authentication cookie
 */
public Cookie settingCookie() {
    // Instantiate a new cookie
    Cookie extAuthCookie = new Cookie("gsa_ad_auth", "true");
    String authCookieDomain = null;
    String authCookiePath = null;

    // Cache cookie properties
    authCookieDomain = valveConf.getAuthCookieDomain();
    authCookiePath = valveConf.getAuthCookiePath();

    // Set extra cookie parameters
    extAuthCookie.setDomain(authCookieDomain);
    extAuthCookie.setPath(authCookiePath);
    extAuthCookie.setMaxAge(authMaxAge);

    // Log info
    logger.debug("Adding cookie: " + extAuthCookie.getName() + ":" + extAuthCookie.getValue() + ":"
            + extAuthCookie.getPath() + ":" + extAuthCookie.getDomain() + ":" + extAuthCookie.getSecure());

    return extAuthCookie;
}

From source file:com.sourcesense.confluence.servlets.CMISProxyServlet.java

/**
 * Retrieves all of the cookies from the servlet request and sets them on
 * the proxy request//w w w  .j av  a 2s .c om
 *
 * @param httpServletRequest     The request object representing the client's
 *                               request to the servlet engine
 * @param httpMethodProxyRequest The request that we are about to send to
 *                               the proxy host
 */
private void setProxyRequestCookies(HttpServletRequest httpServletRequest, HttpMethod httpMethodProxyRequest) {
    // Get an array of all of all the cookies sent by the client
    Cookie[] cookies = httpServletRequest.getCookies();
    if (cookies == null) {
        return;
    }

    for (Cookie cookie : cookies) {
        cookie.setDomain(stringProxyHost);
        cookie.setPath(httpServletRequest.getServletPath());
        httpMethodProxyRequest.setRequestHeader("Cookie",
                cookie.getName() + "=" + cookie.getValue() + "; Path=" + cookie.getPath());
    }
}

From source file:com.qlkh.client.server.proxy.ProxyServlet.java

/**
 * Retrieves all of the cookies from the servlet request and sets them on
 * the proxy request/*w w  w  .  j a v  a 2s .  co  m*/
 *
 * @param httpServletRequest     The request object representing the client's
 *                               request to the servlet engine
 * @param httpMethodProxyRequest The request that we are about to send to
 *                               the proxy host
 */
@SuppressWarnings("unchecked")
private void setProxyRequestCookies(HttpServletRequest httpServletRequest, HttpMethod httpMethodProxyRequest) {
    // Get an array of all of all the cookies sent by the client
    Cookie[] cookies = httpServletRequest.getCookies();
    if (cookies == null) {
        return;
    }

    for (Cookie cookie : cookies) {
        cookie.setDomain(stringProxyHost);
        cookie.setPath(httpServletRequest.getServletPath());
        httpMethodProxyRequest.setRequestHeader("Cookie",
                cookie.getName() + "=" + cookie.getValue() + "; Path=" + cookie.getPath());
    }
}

From source file:com.google.gsa.valve.modules.ldap.LDAPSSO.java

/**
 * Sets the LDAP authentication cookie//from www  .j  a va  2  s  .  c o  m
 * 
 * @return the LDAP authentication cookie
 */
public Cookie settingCookie() {
    // Instantiate a new cookie
    Cookie extAuthCookie = new Cookie(SSO_COOKIE_NAME, "true");
    String authCookieDomain = null;
    String authCookiePath = null;

    // Cache cookie properties
    authCookieDomain = valveConf.getAuthCookieDomain();
    authCookiePath = valveConf.getAuthCookiePath();

    // Set extra cookie parameters
    extAuthCookie.setDomain(authCookieDomain);
    extAuthCookie.setPath(authCookiePath);
    extAuthCookie.setMaxAge(authMaxAge);

    // Log info
    logger.debug("Adding cookie: " + extAuthCookie.getName() + ":" + extAuthCookie.getValue() + ":"
            + extAuthCookie.getPath() + ":" + extAuthCookie.getDomain() + ":" + extAuthCookie.getSecure());

    return extAuthCookie;
}

From source file:com.nesscomputing.httpclient.factory.httpclient4.ApacheHttpClient4Factory.java

private <T> void contributeCookies(final DefaultHttpClient httpClient,
        final HttpClientRequest<T> httpClientRequest) {
    final List<Cookie> cookies = httpClientRequest.getCookies();

    if (CollectionUtils.isNotEmpty(cookies)) {
        final CookieStore cookieStore = new BasicCookieStore();
        for (final Cookie cookie : cookies) {
            final BasicClientCookie httpCookie = new BasicClientCookie(cookie.getName(), cookie.getValue());

            final int maxAge = cookie.getMaxAge();

            if (maxAge > 0) {
                final Date expire = new Date(System.currentTimeMillis() + maxAge * 1000L);
                httpCookie.setExpiryDate(expire);
                httpCookie.setAttribute(ClientCookie.MAX_AGE_ATTR, Integer.toString(maxAge));
            }/*from   w w w . ja  v a 2s  .c  o m*/

            httpCookie.setVersion(1);
            httpCookie.setPath(cookie.getPath());
            httpCookie.setDomain(cookie.getDomain());
            httpCookie.setSecure(cookie.getSecure());

            LOG.debug("Adding cookie to the request: '%s'", httpCookie);
            cookieStore.addCookie(httpCookie);
        }
        httpClient.setCookieStore(cookieStore);
    } else {
        LOG.debug("No cookies found.");
        httpClient.setCookieStore(null);
    }
}