Java Code Examples for org.apache.catalina.util.SessionConfig#getSessionCookieName()

The following examples show how to use org.apache.catalina.util.SessionConfig#getSessionCookieName() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: CoyoteAdapter.java    From Tomcat8-Source-Read with MIT License 4 votes vote down vote up
/**
 * Parse session id in Cookie.
 *
 * @param request The Servlet request object
 */
protected void parseSessionCookiesId(Request request) {

    // If session tracking via cookies has been disabled for the current
    // context, don't go looking for a session ID in a cookie as a cookie
    // from a parent context with a session ID may be present which would
    // overwrite the valid session ID encoded in the URL
    Context context = request.getMappingData().context;
    if (context != null && !context.getServletContext()
            .getEffectiveSessionTrackingModes().contains(
                    SessionTrackingMode.COOKIE)) {
        return;
    }

    // Parse session id from cookies
    ServerCookies serverCookies = request.getServerCookies();
    int count = serverCookies.getCookieCount();
    if (count <= 0) {
        return;
    }

    String sessionCookieName = SessionConfig.getSessionCookieName(context);

    for (int i = 0; i < count; i++) {
        ServerCookie scookie = serverCookies.getCookie(i);
        if (scookie.getName().equals(sessionCookieName)) {
            // Override anything requested in the URL
            if (!request.isRequestedSessionIdFromCookie()) {
                // Accept only the first session id cookie
                convertMB(scookie.getValue());
                request.setRequestedSessionId
                    (scookie.getValue().toString());
                request.setRequestedSessionCookie(true);
                request.setRequestedSessionURL(false);
                if (log.isDebugEnabled()) {
                    log.debug(" Requested cookie session id is " +
                        request.getRequestedSessionId());
                }
            } else {
                if (!request.isRequestedSessionIdValid()) {
                    // Replace the session id until one is valid
                    convertMB(scookie.getValue());
                    request.setRequestedSessionId
                        (scookie.getValue().toString());
                }
            }
        }
    }

}
 
Example 2
Source File: LoadBalancerDrainingValve.java    From Tomcat8-Source-Read with MIT License 4 votes vote down vote up
@Override
public void invoke(Request request, Response response) throws IOException, ServletException {
    if  ("DIS".equals(request.getAttribute(ATTRIBUTE_KEY_JK_LB_ACTIVATION)) &&
            !request.isRequestedSessionIdValid()) {

        if (containerLog.isDebugEnabled()) {
            containerLog.debug("Load-balancer is in DISABLED state; draining this node");
        }

        boolean ignoreRebalance = false;
        Cookie sessionCookie = null;

        final Cookie[] cookies = request.getCookies();

        final String sessionCookieName = SessionConfig.getSessionCookieName(request.getContext());

        if (null != cookies) {
            for (Cookie cookie : cookies) {
                final String cookieName = cookie.getName();
                if (containerLog.isTraceEnabled()) {
                    containerLog.trace("Checking cookie " + cookieName + "=" + cookie.getValue());
                }

                if (sessionCookieName.equals(cookieName) &&
                        request.getRequestedSessionId().equals(cookie.getValue())) {
                    sessionCookie = cookie;
                } else if (null != _ignoreCookieName &&
                        _ignoreCookieName.equals(cookieName) &&
                        null != _ignoreCookieValue &&
                        _ignoreCookieValue.equals(cookie.getValue())) {
                    // The client presenting a valid ignore-cookie value?
                    ignoreRebalance = true;
                }
            }
        }

        if (ignoreRebalance) {
            if (containerLog.isDebugEnabled()) {
                containerLog.debug("Client is presenting a valid " + _ignoreCookieName +
                        " cookie, re-balancing is being skipped");
            }

            getNext().invoke(request, response);

            return;
        }

        // Kill any session cookie that was found
        // TODO: Consider implications of SSO cookies
        if (null != sessionCookie) {
            sessionCookie.setPath(SessionConfig.getSessionCookiePath(request.getContext()));
            sessionCookie.setMaxAge(0); // Delete
            sessionCookie.setValue(""); // Purge the cookie's value
            response.addCookie(sessionCookie);
        }

        // Re-write the URI if it contains a ;jsessionid parameter
        String uri = request.getRequestURI();
        String sessionURIParamName = SessionConfig.getSessionUriParamName(request.getContext());
        if (uri.contains(";" + sessionURIParamName + "=")) {
            uri = uri.replaceFirst(";" + sessionURIParamName + "=[^&?]*", "");
        }

        String queryString = request.getQueryString();

        if (null != queryString) {
            uri = uri + "?" + queryString;
        }

        // NOTE: Do not call response.encodeRedirectURL or the bad
        // sessionid will be restored
        response.setHeader("Location", uri);
        response.setStatus(_redirectStatusCode);
    } else {
        getNext().invoke(request, response);
    }
}
 
Example 3
Source File: ApplicationPushBuilder.java    From Tomcat8-Source-Read with MIT License 4 votes vote down vote up
public ApplicationPushBuilder(Request catalinaRequest, HttpServletRequest request) {

        baseRequest = request;
        this.catalinaRequest = catalinaRequest;
        coyoteRequest = catalinaRequest.getCoyoteRequest();

        // Populate the initial list of HTTP headers
        Enumeration<String> headerNames = request.getHeaderNames();
        while (headerNames.hasMoreElements()) {
            String headerName = headerNames.nextElement();
            List<String> values = new ArrayList<>();
            headers.put(headerName, values);
            Enumeration<String> headerValues = request.getHeaders(headerName);
            while (headerValues.hasMoreElements()) {
                values.add(headerValues.nextElement());
            }
        }

        // Remove the headers
        headers.remove("if-match");
        headers.remove("if-none-match");
        headers.remove("if-modified-since");
        headers.remove("if-unmodified-since");
        headers.remove("if-range");
        headers.remove("range");
        headers.remove("expect");
        headers.remove("authorization");
        headers.remove("referer");
        // Also remove the cookie header since it will be regenerated
        headers.remove("cookie");

        // set the referer header
        StringBuffer referer = request.getRequestURL();
        if (request.getQueryString() != null) {
            referer.append('?');
            referer.append(request.getQueryString());
        }
        addHeader("referer", referer.toString());

        // Session
        Context context = catalinaRequest.getContext();
        sessionCookieName = SessionConfig.getSessionCookieName(context);
        sessionPathParameterName = SessionConfig.getSessionUriParamName(context);

        HttpSession session = request.getSession(false);
        if (session != null) {
            sessionId = session.getId();
        }
        if (sessionId == null) {
            sessionId = request.getRequestedSessionId();
        }
        if (!request.isRequestedSessionIdFromCookie() && !request.isRequestedSessionIdFromURL() &&
                sessionId != null) {
            Set<SessionTrackingMode> sessionTrackingModes =
                    request.getServletContext().getEffectiveSessionTrackingModes();
            addSessionCookie = sessionTrackingModes.contains(SessionTrackingMode.COOKIE);
            addSessionPathParameter = sessionTrackingModes.contains(SessionTrackingMode.URL);
        } else {
            addSessionCookie = request.isRequestedSessionIdFromCookie();
            addSessionPathParameter = request.isRequestedSessionIdFromURL();
        }

        // Cookies
        if (request.getCookies() != null) {
            for (Cookie requestCookie : request.getCookies()) {
                cookies.add(requestCookie);
            }
        }
        for (Cookie responseCookie : catalinaRequest.getResponse().getCookies()) {
            if (responseCookie.getMaxAge() < 0) {
                // Path information not available so can only remove based on
                // name.
                Iterator<Cookie> cookieIterator = cookies.iterator();
                while (cookieIterator.hasNext()) {
                    Cookie cookie = cookieIterator.next();
                    if (cookie.getName().equals(responseCookie.getName())) {
                        cookieIterator.remove();
                    }
                }
            } else {
                cookies.add(new Cookie(responseCookie.getName(), responseCookie.getValue()));
            }
        }
        List<String> cookieValues = new ArrayList<>(1);
        cookieValues.add(generateCookieHeader(cookies,
                catalinaRequest.getContext().getCookieProcessor()));
        headers.put("cookie", cookieValues);

        // Authentication
        if (catalinaRequest.getPrincipal() != null) {
            if ((session == null) || catalinaRequest.getSessionInternal(false).getPrincipal() == null
                    || !(context.getAuthenticator() instanceof AuthenticatorBase)
                    || !((AuthenticatorBase) context.getAuthenticator()).getCache()) {
                // Set a username only if there is no session cache for the principal
                userName = catalinaRequest.getPrincipal().getName();
            }
            setHeader("authorization", "x-push");
        }
    }
 
Example 4
Source File: ApplicationSessionCookieConfig.java    From Tomcat8-Source-Read with MIT License 4 votes vote down vote up
/**
 * Creates a new session cookie for the given session ID
 *
 * @param context     The Context for the web application
 * @param sessionId   The ID of the session for which the cookie will be
 *                    created
 * @param secure      Should session cookie be configured as secure
 * @return the cookie for the session
 */
public static Cookie createSessionCookie(Context context,
        String sessionId, boolean secure) {

    SessionCookieConfig scc =
        context.getServletContext().getSessionCookieConfig();

    // NOTE: The priority order for session cookie configuration is:
    //       1. Context level configuration
    //       2. Values from SessionCookieConfig
    //       3. Defaults

    Cookie cookie = new Cookie(
            SessionConfig.getSessionCookieName(context), sessionId);

    // Just apply the defaults.
    cookie.setMaxAge(scc.getMaxAge());
    cookie.setComment(scc.getComment());

    if (context.getSessionCookieDomain() == null) {
        // Avoid possible NPE
        if (scc.getDomain() != null) {
            cookie.setDomain(scc.getDomain());
        }
    } else {
        cookie.setDomain(context.getSessionCookieDomain());
    }

    // Always set secure if the request is secure
    if (scc.isSecure() || secure) {
        cookie.setSecure(true);
    }

    // Always set httpOnly if the context is configured for that
    if (scc.isHttpOnly() || context.getUseHttpOnly()) {
        cookie.setHttpOnly(true);
    }

    cookie.setPath(SessionConfig.getSessionCookiePath(context));

    return cookie;
}
 
Example 5
Source File: CoyoteAdapter.java    From Tomcat7.0.67 with Apache License 2.0 4 votes vote down vote up
/**
 * Parse session id in URL.
 */
protected void parseSessionCookiesId(org.apache.coyote.Request req, Request request) {

    // If session tracking via cookies has been disabled for the current
    // context, don't go looking for a session ID in a cookie as a cookie
    // from a parent context with a session ID may be present which would
    // overwrite the valid session ID encoded in the URL
    Context context = (Context) request.getMappingData().context;
    if (context != null && !context.getServletContext()
            .getEffectiveSessionTrackingModes().contains(
                    SessionTrackingMode.COOKIE)) {
        return;
    }

    // Parse session id from cookies
    Cookies serverCookies = req.getCookies();
    int count = serverCookies.getCookieCount();
    if (count <= 0) {
        return;
    }

    String sessionCookieName = SessionConfig.getSessionCookieName(context);

    for (int i = 0; i < count; i++) {
        ServerCookie scookie = serverCookies.getCookie(i);
        if (scookie.getName().equals(sessionCookieName)) {
            // Override anything requested in the URL
            if (!request.isRequestedSessionIdFromCookie()) {
                // Accept only the first session id cookie
                convertMB(scookie.getValue());
                request.setRequestedSessionId
                    (scookie.getValue().toString());
                request.setRequestedSessionCookie(true);
                request.setRequestedSessionURL(false);
                if (log.isDebugEnabled()) {
                    log.debug(" Requested cookie session id is " +
                        request.getRequestedSessionId());
                }
            } else {
                if (!request.isRequestedSessionIdValid()) {
                    // Replace the session id until one is valid
                    convertMB(scookie.getValue());
                    request.setRequestedSessionId
                        (scookie.getValue().toString());
                }
            }
        }
    }

}
 
Example 6
Source File: ApplicationSessionCookieConfig.java    From Tomcat7.0.67 with Apache License 2.0 4 votes vote down vote up
/**
 * Creates a new session cookie for the given session ID
 *
 * @param context     The Context for the web application
 * @param sessionId   The ID of the session for which the cookie will be
 *                    created
 * @param secure      Should session cookie be configured as secure
 */
public static Cookie createSessionCookie(Context context,
        String sessionId, boolean secure) {

    SessionCookieConfig scc =
        context.getServletContext().getSessionCookieConfig();

    // NOTE: The priority order for session cookie configuration is:
    //       1. Context level configuration
    //       2. Values from SessionCookieConfig
    //       3. Defaults

    Cookie cookie = new Cookie(
            SessionConfig.getSessionCookieName(context), sessionId);
   
    // Just apply the defaults.
    cookie.setMaxAge(scc.getMaxAge());
    cookie.setComment(scc.getComment());
   
    if (context.getSessionCookieDomain() == null) {
        // Avoid possible NPE
        if (scc.getDomain() != null) {
            cookie.setDomain(scc.getDomain());
        }
    } else {
        cookie.setDomain(context.getSessionCookieDomain());
    }

    // Always set secure if the request is secure
    if (scc.isSecure() || secure) {
        cookie.setSecure(true);
    }

    // Always set httpOnly if the context is configured for that
    if (scc.isHttpOnly() || context.getUseHttpOnly()) {
        cookie.setHttpOnly(true);
    }
   
    String contextPath = context.getSessionCookiePath();
    if (contextPath == null || contextPath.length() == 0) {
        contextPath = scc.getPath();
    }
    if (contextPath == null || contextPath.length() == 0) {
        contextPath = context.getEncodedPath();
    }
    if (context.getSessionCookiePathUsesTrailingSlash()) {
        // Handle special case of ROOT context where cookies require a path of
        // '/' but the servlet spec uses an empty string
        // Also ensure the cookies for a context with a path of /foo don't get
        // sent for requests with a path of /foobar
        if (!contextPath.endsWith("/")) {
            contextPath = contextPath + "/";
        }
    } else {
        // Only handle special case of ROOT context where cookies require a
        // path of '/' but the servlet spec uses an empty string
        if (contextPath.length() == 0) {
            contextPath = "/";
        }
    }
    cookie.setPath(contextPath);

    return cookie;
}
 
Example 7
Source File: CoyoteAdapter.java    From tomcatsrc with Apache License 2.0 4 votes vote down vote up
/**
 * Parse session id in URL.
 */
protected void parseSessionCookiesId(org.apache.coyote.Request req, Request request) {

    // If session tracking via cookies has been disabled for the current
    // context, don't go looking for a session ID in a cookie as a cookie
    // from a parent context with a session ID may be present which would
    // overwrite the valid session ID encoded in the URL
    Context context = (Context) request.getMappingData().context;
    if (context != null && !context.getServletContext()
            .getEffectiveSessionTrackingModes().contains(
                    SessionTrackingMode.COOKIE)) {
        return;
    }

    // Parse session id from cookies
    Cookies serverCookies = req.getCookies();
    int count = serverCookies.getCookieCount();
    if (count <= 0) {
        return;
    }

    String sessionCookieName = SessionConfig.getSessionCookieName(context);

    for (int i = 0; i < count; i++) {
        ServerCookie scookie = serverCookies.getCookie(i);
        if (scookie.getName().equals(sessionCookieName)) {
            // Override anything requested in the URL
            if (!request.isRequestedSessionIdFromCookie()) {
                // Accept only the first session id cookie
                convertMB(scookie.getValue());
                request.setRequestedSessionId
                    (scookie.getValue().toString());
                request.setRequestedSessionCookie(true);
                request.setRequestedSessionURL(false);
                if (log.isDebugEnabled()) {
                    log.debug(" Requested cookie session id is " +
                        request.getRequestedSessionId());
                }
            } else {
                if (!request.isRequestedSessionIdValid()) {
                    // Replace the session id until one is valid
                    convertMB(scookie.getValue());
                    request.setRequestedSessionId
                        (scookie.getValue().toString());
                }
            }
        }
    }

}
 
Example 8
Source File: ApplicationSessionCookieConfig.java    From tomcatsrc with Apache License 2.0 4 votes vote down vote up
/**
 * Creates a new session cookie for the given session ID
 *
 * @param context     The Context for the web application
 * @param sessionId   The ID of the session for which the cookie will be
 *                    created
 * @param secure      Should session cookie be configured as secure
 */
public static Cookie createSessionCookie(Context context,
        String sessionId, boolean secure) {

    SessionCookieConfig scc =
        context.getServletContext().getSessionCookieConfig();

    // NOTE: The priority order for session cookie configuration is:
    //       1. Context level configuration
    //       2. Values from SessionCookieConfig
    //       3. Defaults

    Cookie cookie = new Cookie(
            SessionConfig.getSessionCookieName(context), sessionId);
   
    // Just apply the defaults.
    cookie.setMaxAge(scc.getMaxAge());
    cookie.setComment(scc.getComment());
   
    if (context.getSessionCookieDomain() == null) {
        // Avoid possible NPE
        if (scc.getDomain() != null) {
            cookie.setDomain(scc.getDomain());
        }
    } else {
        cookie.setDomain(context.getSessionCookieDomain());
    }

    // Always set secure if the request is secure
    if (scc.isSecure() || secure) {
        cookie.setSecure(true);
    }

    // Always set httpOnly if the context is configured for that
    if (scc.isHttpOnly() || context.getUseHttpOnly()) {
        cookie.setHttpOnly(true);
    }
   
    String contextPath = context.getSessionCookiePath();
    if (contextPath == null || contextPath.length() == 0) {
        contextPath = scc.getPath();
    }
    if (contextPath == null || contextPath.length() == 0) {
        contextPath = context.getEncodedPath();
    }
    if (context.getSessionCookiePathUsesTrailingSlash()) {
        // Handle special case of ROOT context where cookies require a path of
        // '/' but the servlet spec uses an empty string
        // Also ensure the cookies for a context with a path of /foo don't get
        // sent for requests with a path of /foobar
        if (!contextPath.endsWith("/")) {
            contextPath = contextPath + "/";
        }
    } else {
        // Only handle special case of ROOT context where cookies require a
        // path of '/' but the servlet spec uses an empty string
        if (contextPath.length() == 0) {
            contextPath = "/";
        }
    }
    cookie.setPath(contextPath);

    return cookie;
}
 
Example 9
Source File: ApplicationSessionCookieConfig.java    From Tomcat7.0.67 with Apache License 2.0 2 votes vote down vote up
/**
 * Determine the name to use for the session cookie for the provided
 * context.
 * @param context
 *
 * @deprecated  Replaced by
 *              {@link SessionConfig#getSessionCookieName(Context)}. This
 *              will be removed in Tomcat 8.0.x.
 */
@Deprecated
public static String getSessionCookieName(Context context) {
    return SessionConfig.getSessionCookieName(context);
}
 
Example 10
Source File: ApplicationSessionCookieConfig.java    From tomcatsrc with Apache License 2.0 2 votes vote down vote up
/**
 * Determine the name to use for the session cookie for the provided
 * context.
 * @param context
 *
 * @deprecated  Replaced by
 *              {@link SessionConfig#getSessionCookieName(Context)}. This
 *              will be removed in Tomcat 8.0.x.
 */
@Deprecated
public static String getSessionCookieName(Context context) {
    return SessionConfig.getSessionCookieName(context);
}