Search in sources :

Example 71 with HttpSession

use of jakarta.servlet.http.HttpSession in project spring-framework by spring-projects.

the class ServletRequestAttributesTests method doSkipImmutableValue.

private void doSkipImmutableValue(Object immutableValue) {
    HttpServletRequest request = mock(HttpServletRequest.class);
    HttpSession session = mock(HttpSession.class);
    given(request.getSession(anyBoolean())).willReturn(session);
    given(session.getAttribute(KEY)).willReturn(immutableValue);
    ServletRequestAttributes attrs = new ServletRequestAttributes(request);
    attrs.getAttribute(KEY, RequestAttributes.SCOPE_SESSION);
    attrs.requestCompleted();
    verify(session, times(2)).getAttribute(KEY);
    verifyNoMoreInteractions(session);
}
Also used : HttpServletRequest(jakarta.servlet.http.HttpServletRequest) MockHttpServletRequest(org.springframework.web.testfixture.servlet.MockHttpServletRequest) MockHttpSession(org.springframework.web.testfixture.servlet.MockHttpSession) HttpSession(jakarta.servlet.http.HttpSession)

Example 72 with HttpSession

use of jakarta.servlet.http.HttpSession in project tomcat by apache.

the class CsrfPreventionFilter method doFilter.

@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
    ServletResponse wResponse = null;
    if (request instanceof HttpServletRequest && response instanceof HttpServletResponse) {
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse res = (HttpServletResponse) response;
        boolean skipNonceCheck = false;
        if (Constants.METHOD_GET.equals(req.getMethod()) && entryPoints.contains(getRequestedPath(req))) {
            if (log.isTraceEnabled()) {
                log.trace("Skipping CSRF nonce-check for GET request to entry point " + getRequestedPath(req));
            }
            skipNonceCheck = true;
        }
        HttpSession session = req.getSession(false);
        @SuppressWarnings("unchecked") LruCache<String> nonceCache = (session == null) ? null : (LruCache<String>) session.getAttribute(Constants.CSRF_NONCE_SESSION_ATTR_NAME);
        if (!skipNonceCheck) {
            String previousNonce = req.getParameter(nonceRequestParameterName);
            if (previousNonce == null) {
                if (log.isDebugEnabled()) {
                    log.debug("Rejecting request for " + getRequestedPath(req) + ", session " + (null == session ? "(none)" : session.getId()) + " with no CSRF nonce found in request");
                }
                res.sendError(getDenyStatus());
                return;
            } else if (nonceCache == null) {
                if (log.isDebugEnabled()) {
                    log.debug("Rejecting request for " + getRequestedPath(req) + ", session " + (null == session ? "(none)" : session.getId()) + " due to empty / missing nonce cache");
                }
                res.sendError(getDenyStatus());
                return;
            } else if (!nonceCache.contains(previousNonce)) {
                if (log.isDebugEnabled()) {
                    log.debug("Rejecting request for " + getRequestedPath(req) + ", session " + (null == session ? "(none)" : session.getId()) + " due to invalid nonce " + previousNonce);
                }
                res.sendError(getDenyStatus());
                return;
            }
            if (log.isTraceEnabled()) {
                log.trace("Allowing request to " + getRequestedPath(req) + " with valid CSRF nonce " + previousNonce);
            }
        }
        if (nonceCache == null) {
            if (log.isDebugEnabled()) {
                log.debug("Creating new CSRF nonce cache with size=" + nonceCacheSize + " for session " + (null == session ? "(will create)" : session.getId()));
            }
            nonceCache = new LruCache<>(nonceCacheSize);
            if (session == null) {
                if (log.isDebugEnabled()) {
                    log.debug("Creating new session to store CSRF nonce cache");
                }
                session = req.getSession(true);
            }
            session.setAttribute(Constants.CSRF_NONCE_SESSION_ATTR_NAME, nonceCache);
        }
        String newNonce = generateNonce();
        nonceCache.add(newNonce);
        // Take this request's nonce and put it into the request
        // attributes so pages can make direct use of it, rather than
        // requiring the use of response.encodeURL.
        request.setAttribute(Constants.CSRF_NONCE_REQUEST_ATTR_NAME, newNonce);
        wResponse = new CsrfResponseWrapper(res, nonceRequestParameterName, newNonce);
    } else {
        wResponse = response;
    }
    chain.doFilter(request, wResponse);
}
Also used : HttpServletRequest(jakarta.servlet.http.HttpServletRequest) ServletResponse(jakarta.servlet.ServletResponse) HttpServletResponse(jakarta.servlet.http.HttpServletResponse) HttpSession(jakarta.servlet.http.HttpSession) HttpServletResponse(jakarta.servlet.http.HttpServletResponse)

Example 73 with HttpSession

use of jakarta.servlet.http.HttpSession in project tomcat by apache.

the class SessionUtils method guessUserFromSession.

/**
 * Try to get user from the session, if possible.
 * @param in_session The session
 * @return the user
 */
public static Object guessUserFromSession(final Session in_session) {
    if (null == in_session) {
        return null;
    }
    if (in_session.getPrincipal() != null) {
        return in_session.getPrincipal().getName();
    }
    HttpSession httpSession = in_session.getSession();
    if (httpSession == null) {
        return null;
    }
    try {
        Object user = null;
        // First search "known locations"
        for (String userTestAttribute : USER_TEST_ATTRIBUTES) {
            Object obj = httpSession.getAttribute(userTestAttribute);
            if (null != obj) {
                user = obj;
                break;
            }
            obj = httpSession.getAttribute(userTestAttribute.toLowerCase(Locale.ENGLISH));
            if (null != obj) {
                user = obj;
                break;
            }
            obj = httpSession.getAttribute(userTestAttribute.toUpperCase(Locale.ENGLISH));
            if (null != obj) {
                user = obj;
                break;
            }
        }
        if (null != user) {
            return user;
        }
        // Last guess: iterate over all attributes, to find a java.security.Principal or javax.security.auth.Subject
        // If there is only one, consider it to be /the/ user
        final List<Object> principalArray = new ArrayList<>();
        for (Enumeration<String> enumeration = httpSession.getAttributeNames(); enumeration.hasMoreElements(); ) {
            String name = enumeration.nextElement();
            Object obj = httpSession.getAttribute(name);
            if (obj instanceof Principal || obj instanceof Subject) {
                principalArray.add(obj);
            }
        }
        if (principalArray.size() == 1) {
            user = principalArray.get(0);
        }
        if (null != user) {
            return user;
        }
        return user;
    } catch (IllegalStateException ise) {
        // ignore: invalidated session
        return null;
    }
}
Also used : HttpSession(jakarta.servlet.http.HttpSession) ArrayList(java.util.ArrayList) Principal(java.security.Principal) Subject(javax.security.auth.Subject)

Example 74 with HttpSession

use of jakarta.servlet.http.HttpSession in project tomcat by apache.

the class ApplicationHttpRequest method getSession.

/**
 * Return the session associated with this Request, creating one
 * if necessary and requested.
 *
 * @param create Create a new session if one does not exist
 */
@Override
public HttpSession getSession(boolean create) {
    if (crossContext) {
        // There cannot be a session if no context has been assigned yet
        if (context == null) {
            return null;
        }
        // Return the current session if it exists and is valid
        if (session != null && session.isValid()) {
            return session.getSession();
        }
        HttpSession other = super.getSession(false);
        if (create && (other == null)) {
            // First create a session in the first context: the problem is
            // that the top level request is the only one which can
            // create the cookie safely
            other = super.getSession(true);
        }
        if (other != null) {
            Session localSession = null;
            try {
                localSession = context.getManager().findSession(other.getId());
                if (localSession != null && !localSession.isValid()) {
                    localSession = null;
                }
            } catch (IOException e) {
            // Ignore
            }
            if (localSession == null && create) {
                localSession = context.getManager().createSession(other.getId());
            }
            if (localSession != null) {
                localSession.access();
                session = localSession;
                return session.getSession();
            }
        }
        return null;
    } else {
        return super.getSession(create);
    }
}
Also used : HttpSession(jakarta.servlet.http.HttpSession) IOException(java.io.IOException) HttpSession(jakarta.servlet.http.HttpSession) Session(org.apache.catalina.Session)

Example 75 with HttpSession

use of jakarta.servlet.http.HttpSession in project tomcat by apache.

the class CGIServlet method printServletEnvironment.

/**
 * Logs important Servlet API and container information.
 *
 * <p>
 * Based on SnoopAllServlet by Craig R. McClanahan
 * </p>
 *
 * @param  req    HttpServletRequest object used as source of information
 *
 * @exception  IOException  if a write operation exception occurs
 */
private void printServletEnvironment(HttpServletRequest req) throws IOException {
    // Document the properties from ServletRequest
    log.trace("ServletRequest Properties");
    Enumeration<String> attrs = req.getAttributeNames();
    while (attrs.hasMoreElements()) {
        String attr = attrs.nextElement();
        log.trace("Request Attribute: " + attr + ": [ " + req.getAttribute(attr) + "]");
    }
    log.trace("Character Encoding: [" + req.getCharacterEncoding() + "]");
    log.trace("Content Length: [" + req.getContentLengthLong() + "]");
    log.trace("Content Type: [" + req.getContentType() + "]");
    Enumeration<Locale> locales = req.getLocales();
    while (locales.hasMoreElements()) {
        Locale locale = locales.nextElement();
        log.trace("Locale: [" + locale + "]");
    }
    Enumeration<String> params = req.getParameterNames();
    while (params.hasMoreElements()) {
        String param = params.nextElement();
        for (String value : req.getParameterValues(param)) {
            log.trace("Request Parameter: " + param + ":  [" + value + "]");
        }
    }
    log.trace("Protocol: [" + req.getProtocol() + "]");
    log.trace("Remote Address: [" + req.getRemoteAddr() + "]");
    log.trace("Remote Host: [" + req.getRemoteHost() + "]");
    log.trace("Scheme: [" + req.getScheme() + "]");
    log.trace("Secure: [" + req.isSecure() + "]");
    log.trace("Server Name: [" + req.getServerName() + "]");
    log.trace("Server Port: [" + req.getServerPort() + "]");
    // Document the properties from HttpServletRequest
    log.trace("HttpServletRequest Properties");
    log.trace("Auth Type: [" + req.getAuthType() + "]");
    log.trace("Context Path: [" + req.getContextPath() + "]");
    Cookie[] cookies = req.getCookies();
    if (cookies != null) {
        for (Cookie cookie : cookies) {
            log.trace("Cookie: " + cookie.getName() + ": [" + cookie.getValue() + "]");
        }
    }
    Enumeration<String> headers = req.getHeaderNames();
    while (headers.hasMoreElements()) {
        String header = headers.nextElement();
        log.trace("HTTP Header: " + header + ": [" + req.getHeader(header) + "]");
    }
    log.trace("Method: [" + req.getMethod() + "]");
    log.trace("Path Info: [" + req.getPathInfo() + "]");
    log.trace("Path Translated: [" + req.getPathTranslated() + "]");
    log.trace("Query String: [" + req.getQueryString() + "]");
    log.trace("Remote User: [" + req.getRemoteUser() + "]");
    log.trace("Requested Session ID: [" + req.getRequestedSessionId() + "]");
    log.trace("Requested Session ID From Cookie: [" + req.isRequestedSessionIdFromCookie() + "]");
    log.trace("Requested Session ID From URL: [" + req.isRequestedSessionIdFromURL() + "]");
    log.trace("Requested Session ID Valid: [" + req.isRequestedSessionIdValid() + "]");
    log.trace("Request URI: [" + req.getRequestURI() + "]");
    log.trace("Servlet Path: [" + req.getServletPath() + "]");
    log.trace("User Principal: [" + req.getUserPrincipal() + "]");
    // Process the current session (if there is one)
    HttpSession session = req.getSession(false);
    if (session != null) {
        // Document the session properties
        log.trace("HttpSession Properties");
        log.trace("ID: [" + session.getId() + "]");
        log.trace("Creation Time: [" + new Date(session.getCreationTime()) + "]");
        log.trace("Last Accessed Time: [" + new Date(session.getLastAccessedTime()) + "]");
        log.trace("Max Inactive Interval: [" + session.getMaxInactiveInterval() + "]");
        // Document the session attributes
        attrs = session.getAttributeNames();
        while (attrs.hasMoreElements()) {
            String attr = attrs.nextElement();
            log.trace("Session Attribute: " + attr + ": [" + session.getAttribute(attr) + "]");
        }
    }
    // Document the servlet configuration properties
    log.trace("ServletConfig Properties");
    log.trace("Servlet Name: [" + getServletConfig().getServletName() + "]");
    // Document the servlet configuration initialization parameters
    params = getServletConfig().getInitParameterNames();
    while (params.hasMoreElements()) {
        String param = params.nextElement();
        String value = getServletConfig().getInitParameter(param);
        log.trace("Servlet Init Param: " + param + ": [" + value + "]");
    }
    // Document the servlet context properties
    log.trace("ServletContext Properties");
    log.trace("Major Version: [" + getServletContext().getMajorVersion() + "]");
    log.trace("Minor Version: [" + getServletContext().getMinorVersion() + "]");
    log.trace("Real Path for '/': [" + getServletContext().getRealPath("/") + "]");
    log.trace("Server Info: [" + getServletContext().getServerInfo() + "]");
    // Document the servlet context initialization parameters
    log.trace("ServletContext Initialization Parameters");
    params = getServletContext().getInitParameterNames();
    while (params.hasMoreElements()) {
        String param = params.nextElement();
        String value = getServletContext().getInitParameter(param);
        log.trace("Servlet Context Init Param: " + param + ": [" + value + "]");
    }
    // Document the servlet context attributes
    log.trace("ServletContext Attributes");
    attrs = getServletContext().getAttributeNames();
    while (attrs.hasMoreElements()) {
        String attr = attrs.nextElement();
        log.trace("Servlet Context Attribute: " + attr + ": [" + getServletContext().getAttribute(attr) + "]");
    }
}
Also used : Locale(java.util.Locale) Cookie(jakarta.servlet.http.Cookie) HttpSession(jakarta.servlet.http.HttpSession) Date(java.util.Date)

Aggregations

HttpSession (jakarta.servlet.http.HttpSession)101 Test (org.junit.jupiter.api.Test)39 MockHttpServletRequest (org.springframework.mock.web.MockHttpServletRequest)17 MvcResult (org.springframework.test.web.servlet.MvcResult)16 HttpServletRequest (jakarta.servlet.http.HttpServletRequest)13 MockHttpServletResponse (org.springframework.mock.web.MockHttpServletResponse)12 MockHttpSession (org.springframework.mock.web.MockHttpSession)12 Map (java.util.Map)11 MockHttpServletRequest (org.springframework.web.testfixture.servlet.MockHttpServletRequest)11 MockHttpServletResponse (org.springframework.web.testfixture.servlet.MockHttpServletResponse)9 SecurityContext (org.springframework.security.core.context.SecurityContext)7 PathPatternsParameterizedTest (org.springframework.web.servlet.handler.PathPatternsParameterizedTest)7 Authentication (org.springframework.security.core.Authentication)6 Cookie (jakarta.servlet.http.Cookie)5 Request (org.apache.catalina.connector.Request)5 OAuth2AuthorizedClient (org.springframework.security.oauth2.client.OAuth2AuthorizedClient)5 SessionFixationProtectionStrategy (org.springframework.security.web.authentication.session.SessionFixationProtectionStrategy)5 IOException (java.io.IOException)4 PrintWriter (java.io.PrintWriter)4 Response (org.apache.catalina.connector.Response)4