Search in sources :

Example 56 with HttpSession

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

the class NamespaceHttpTests method configureWhenSessionCreationPolicyIfRequiredThenSessionCreatedWhenRequiredOnRequest.

// http@create-session=ifRequired
@Test
public void configureWhenSessionCreationPolicyIfRequiredThenSessionCreatedWhenRequiredOnRequest() throws Exception {
    this.spring.register(IfRequiredConfig.class).autowire();
    MvcResult mvcResult = this.mockMvc.perform(get("/unsecure")).andReturn();
    HttpSession session = mvcResult.getRequest().getSession(false);
    assertThat(session).isNull();
    mvcResult = this.mockMvc.perform(formLogin()).andReturn();
    session = mvcResult.getRequest().getSession(false);
    assertThat(session).isNotNull();
    assertThat(session.isNew()).isTrue();
}
Also used : HttpSession(jakarta.servlet.http.HttpSession) MvcResult(org.springframework.test.web.servlet.MvcResult) Test(org.junit.jupiter.api.Test)

Example 57 with HttpSession

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

the class ServletRequestAttributes method removeAttribute.

@Override
public void removeAttribute(String name, int scope) {
    if (scope == SCOPE_REQUEST) {
        if (isRequestActive()) {
            removeRequestDestructionCallback(name);
            this.request.removeAttribute(name);
        }
    } else {
        HttpSession session = getSession(false);
        if (session != null) {
            this.sessionAttributesToUpdate.remove(name);
            try {
                session.removeAttribute(DESTRUCTION_CALLBACK_NAME_PREFIX + name);
                session.removeAttribute(name);
            } catch (IllegalStateException ex) {
            // Session invalidated - shouldn't usually happen.
            }
        }
    }
}
Also used : HttpSession(jakarta.servlet.http.HttpSession)

Example 58 with HttpSession

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

the class ServletRequestAttributes method updateAccessedSessionAttributes.

/**
 * Update all accessed session attributes through {@code session.setAttribute}
 * calls, explicitly indicating to the container that they might have been modified.
 */
@Override
protected void updateAccessedSessionAttributes() {
    if (!this.sessionAttributesToUpdate.isEmpty()) {
        // Update all affected session attributes.
        HttpSession session = getSession(false);
        if (session != null) {
            try {
                for (Map.Entry<String, Object> entry : this.sessionAttributesToUpdate.entrySet()) {
                    String name = entry.getKey();
                    Object newValue = entry.getValue();
                    Object oldValue = session.getAttribute(name);
                    if (oldValue == newValue && !isImmutableSessionAttribute(name, newValue)) {
                        session.setAttribute(name, newValue);
                    }
                }
            } catch (IllegalStateException ex) {
            // Session invalidated - shouldn't usually happen.
            }
        }
        this.sessionAttributesToUpdate.clear();
    }
}
Also used : HttpSession(jakarta.servlet.http.HttpSession) Map(java.util.Map) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap)

Example 59 with HttpSession

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

the class ServletWebRequest method getDescription.

@Override
public String getDescription(boolean includeClientInfo) {
    HttpServletRequest request = getRequest();
    StringBuilder sb = new StringBuilder();
    sb.append("uri=").append(request.getRequestURI());
    if (includeClientInfo) {
        String client = request.getRemoteAddr();
        if (StringUtils.hasLength(client)) {
            sb.append(";client=").append(client);
        }
        HttpSession session = request.getSession(false);
        if (session != null) {
            sb.append(";session=").append(session.getId());
        }
        String user = request.getRemoteUser();
        if (StringUtils.hasLength(user)) {
            sb.append(";user=").append(user);
        }
    }
    return sb.toString();
}
Also used : HttpServletRequest(jakarta.servlet.http.HttpServletRequest) HttpSession(jakarta.servlet.http.HttpSession)

Example 60 with HttpSession

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

the class AbstractTemplateView method renderMergedOutputModel.

@Override
protected final void renderMergedOutputModel(Map<String, Object> model, HttpServletRequest request, HttpServletResponse response) throws Exception {
    if (this.exposeRequestAttributes) {
        Map<String, Object> exposed = null;
        for (Enumeration<String> en = request.getAttributeNames(); en.hasMoreElements(); ) {
            String attribute = en.nextElement();
            if (model.containsKey(attribute) && !this.allowRequestOverride) {
                throw new ServletException("Cannot expose request attribute '" + attribute + "' because of an existing model object of the same name");
            }
            Object attributeValue = request.getAttribute(attribute);
            if (logger.isDebugEnabled()) {
                exposed = exposed != null ? exposed : new LinkedHashMap<>();
                exposed.put(attribute, attributeValue);
            }
            model.put(attribute, attributeValue);
        }
        if (logger.isTraceEnabled() && exposed != null) {
            logger.trace("Exposed request attributes to model: " + exposed);
        }
    }
    if (this.exposeSessionAttributes) {
        HttpSession session = request.getSession(false);
        if (session != null) {
            Map<String, Object> exposed = null;
            for (Enumeration<String> en = session.getAttributeNames(); en.hasMoreElements(); ) {
                String attribute = en.nextElement();
                if (model.containsKey(attribute) && !this.allowSessionOverride) {
                    throw new ServletException("Cannot expose session attribute '" + attribute + "' because of an existing model object of the same name");
                }
                Object attributeValue = session.getAttribute(attribute);
                if (logger.isDebugEnabled()) {
                    exposed = exposed != null ? exposed : new LinkedHashMap<>();
                    exposed.put(attribute, attributeValue);
                }
                model.put(attribute, attributeValue);
            }
            if (logger.isTraceEnabled() && exposed != null) {
                logger.trace("Exposed session attributes to model: " + exposed);
            }
        }
    }
    if (this.exposeSpringMacroHelpers) {
        if (model.containsKey(SPRING_MACRO_REQUEST_CONTEXT_ATTRIBUTE)) {
            throw new ServletException("Cannot expose bind macro helper '" + SPRING_MACRO_REQUEST_CONTEXT_ATTRIBUTE + "' because of an existing model object of the same name");
        }
        // Expose RequestContext instance for Spring macros.
        model.put(SPRING_MACRO_REQUEST_CONTEXT_ATTRIBUTE, new RequestContext(request, response, getServletContext(), model));
    }
    applyContentType(response);
    if (logger.isDebugEnabled()) {
        logger.debug("Rendering [" + getUrl() + "]");
    }
    renderMergedTemplateModel(model, request, response);
}
Also used : ServletException(jakarta.servlet.ServletException) HttpSession(jakarta.servlet.http.HttpSession) RequestContext(org.springframework.web.servlet.support.RequestContext) LinkedHashMap(java.util.LinkedHashMap)

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