Search in sources :

Example 91 with HttpSession

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

the class DefaultSessionAuthenticationStrategyTests method newSessionIsCreatedIfSessionAlreadyExistsWithEventPublisher.

// SEC-2002
@Test
public void newSessionIsCreatedIfSessionAlreadyExistsWithEventPublisher() {
    SessionFixationProtectionStrategy strategy = new SessionFixationProtectionStrategy();
    HttpServletRequest request = new MockHttpServletRequest();
    HttpSession session = request.getSession();
    session.setAttribute("blah", "blah");
    session.setAttribute("SPRING_SECURITY_SAVED_REQUEST_KEY", "DefaultSavedRequest");
    String oldSessionId = session.getId();
    ApplicationEventPublisher eventPublisher = mock(ApplicationEventPublisher.class);
    strategy.setApplicationEventPublisher(eventPublisher);
    Authentication mockAuthentication = mock(Authentication.class);
    strategy.onAuthentication(mockAuthentication, request, new MockHttpServletResponse());
    ArgumentCaptor<ApplicationEvent> eventArgumentCaptor = ArgumentCaptor.forClass(ApplicationEvent.class);
    verify(eventPublisher).publishEvent(eventArgumentCaptor.capture());
    assertThat(oldSessionId.equals(request.getSession().getId())).isFalse();
    assertThat(request.getSession().getAttribute("blah")).isNotNull();
    assertThat(request.getSession().getAttribute("SPRING_SECURITY_SAVED_REQUEST_KEY")).isNotNull();
    assertThat(eventArgumentCaptor.getValue()).isNotNull();
    assertThat(eventArgumentCaptor.getValue() instanceof SessionFixationProtectionEvent).isTrue();
    SessionFixationProtectionEvent event = (SessionFixationProtectionEvent) eventArgumentCaptor.getValue();
    assertThat(event.getOldSessionId()).isEqualTo(oldSessionId);
    assertThat(event.getNewSessionId()).isEqualTo(request.getSession().getId());
    assertThat(event.getAuthentication()).isSameAs(mockAuthentication);
}
Also used : HttpServletRequest(jakarta.servlet.http.HttpServletRequest) MockHttpServletRequest(org.springframework.mock.web.MockHttpServletRequest) MockHttpServletRequest(org.springframework.mock.web.MockHttpServletRequest) HttpSession(jakarta.servlet.http.HttpSession) Authentication(org.springframework.security.core.Authentication) SessionFixationProtectionEvent(org.springframework.security.web.authentication.session.SessionFixationProtectionEvent) ApplicationEventPublisher(org.springframework.context.ApplicationEventPublisher) ApplicationEvent(org.springframework.context.ApplicationEvent) SessionFixationProtectionStrategy(org.springframework.security.web.authentication.session.SessionFixationProtectionStrategy) MockHttpServletResponse(org.springframework.mock.web.MockHttpServletResponse) Test(org.junit.jupiter.api.Test)

Example 92 with HttpSession

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

the class SessionFixationProtectionStrategy method applySessionFixation.

@Override
final HttpSession applySessionFixation(HttpServletRequest request) {
    HttpSession session = request.getSession();
    String originalSessionId = session.getId();
    this.logger.debug(LogMessage.of(() -> "Invalidating session with Id '" + originalSessionId + "' " + (this.migrateSessionAttributes ? "and" : "without") + " migrating attributes."));
    Map<String, Object> attributesToMigrate = extractAttributes(session);
    int maxInactiveIntervalToMigrate = session.getMaxInactiveInterval();
    session.invalidate();
    // we now have a new session
    session = request.getSession(true);
    this.logger.debug(LogMessage.format("Started new session: %s", session.getId()));
    transferAttributes(attributesToMigrate, session);
    if (this.migrateSessionAttributes) {
        session.setMaxInactiveInterval(maxInactiveIntervalToMigrate);
    }
    return session;
}
Also used : HttpSession(jakarta.servlet.http.HttpSession)

Example 93 with HttpSession

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

the class DefaultLoginPageGeneratingFilter method generateLoginPageHtml.

private String generateLoginPageHtml(HttpServletRequest request, boolean loginError, boolean logoutSuccess) {
    String errorMsg = "Invalid credentials";
    if (loginError) {
        HttpSession session = request.getSession(false);
        if (session != null) {
            AuthenticationException ex = (AuthenticationException) session.getAttribute(WebAttributes.AUTHENTICATION_EXCEPTION);
            errorMsg = (ex != null) ? ex.getMessage() : "Invalid credentials";
        }
    }
    String contextPath = request.getContextPath();
    StringBuilder sb = new StringBuilder();
    sb.append("<!DOCTYPE html>\n");
    sb.append("<html lang=\"en\">\n");
    sb.append("  <head>\n");
    sb.append("    <meta charset=\"utf-8\">\n");
    sb.append("    <meta name=\"viewport\" content=\"width=device-width, initial-scale=1, shrink-to-fit=no\">\n");
    sb.append("    <meta name=\"description\" content=\"\">\n");
    sb.append("    <meta name=\"author\" content=\"\">\n");
    sb.append("    <title>Please sign in</title>\n");
    sb.append("    <link href=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/css/bootstrap.min.css\" " + "rel=\"stylesheet\" integrity=\"sha384-/Y6pD6FV/Vv2HJnA6t+vslU6fwYXjCFtcEpHbNJ0lyAFsXTsjBbfaDjzALeQsN6M\" crossorigin=\"anonymous\">\n");
    sb.append("    <link href=\"https://getbootstrap.com/docs/4.0/examples/signin/signin.css\" " + "rel=\"stylesheet\" crossorigin=\"anonymous\"/>\n");
    sb.append("  </head>\n");
    sb.append("  <body>\n");
    sb.append("     <div class=\"container\">\n");
    if (this.formLoginEnabled) {
        sb.append("      <form class=\"form-signin\" method=\"post\" action=\"" + contextPath + this.authenticationUrl + "\">\n");
        sb.append("        <h2 class=\"form-signin-heading\">Please sign in</h2>\n");
        sb.append(createError(loginError, errorMsg) + createLogoutSuccess(logoutSuccess) + "        <p>\n");
        sb.append("          <label for=\"username\" class=\"sr-only\">Username</label>\n");
        sb.append("          <input type=\"text\" id=\"username\" name=\"" + this.usernameParameter + "\" class=\"form-control\" placeholder=\"Username\" required autofocus>\n");
        sb.append("        </p>\n");
        sb.append("        <p>\n");
        sb.append("          <label for=\"password\" class=\"sr-only\">Password</label>\n");
        sb.append("          <input type=\"password\" id=\"password\" name=\"" + this.passwordParameter + "\" class=\"form-control\" placeholder=\"Password\" required>\n");
        sb.append("        </p>\n");
        sb.append(createRememberMe(this.rememberMeParameter) + renderHiddenInputs(request));
        sb.append("        <button class=\"btn btn-lg btn-primary btn-block\" type=\"submit\">Sign in</button>\n");
        sb.append("      </form>\n");
    }
    if (this.oauth2LoginEnabled) {
        sb.append("<h2 class=\"form-signin-heading\">Login with OAuth 2.0</h2>");
        sb.append(createError(loginError, errorMsg));
        sb.append(createLogoutSuccess(logoutSuccess));
        sb.append("<table class=\"table table-striped\">\n");
        for (Map.Entry<String, String> clientAuthenticationUrlToClientName : this.oauth2AuthenticationUrlToClientName.entrySet()) {
            sb.append(" <tr><td>");
            String url = clientAuthenticationUrlToClientName.getKey();
            sb.append("<a href=\"").append(contextPath).append(url).append("\">");
            String clientName = HtmlUtils.htmlEscape(clientAuthenticationUrlToClientName.getValue());
            sb.append(clientName);
            sb.append("</a>");
            sb.append("</td></tr>\n");
        }
        sb.append("</table>\n");
    }
    if (this.saml2LoginEnabled) {
        sb.append("<h2 class=\"form-signin-heading\">Login with SAML 2.0</h2>");
        sb.append(createError(loginError, errorMsg));
        sb.append(createLogoutSuccess(logoutSuccess));
        sb.append("<table class=\"table table-striped\">\n");
        for (Map.Entry<String, String> relyingPartyUrlToName : this.saml2AuthenticationUrlToProviderName.entrySet()) {
            sb.append(" <tr><td>");
            String url = relyingPartyUrlToName.getKey();
            sb.append("<a href=\"").append(contextPath).append(url).append("\">");
            String partyName = HtmlUtils.htmlEscape(relyingPartyUrlToName.getValue());
            sb.append(partyName);
            sb.append("</a>");
            sb.append("</td></tr>\n");
        }
        sb.append("</table>\n");
    }
    sb.append("</div>\n");
    sb.append("</body></html>");
    return sb.toString();
}
Also used : AuthenticationException(org.springframework.security.core.AuthenticationException) HttpSession(jakarta.servlet.http.HttpSession) Map(java.util.Map)

Example 94 with HttpSession

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

the class SecurityContextPersistenceFilter method doFilter.

private void doFilter(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException {
    // ensure that filter is only applied once per request
    if (request.getAttribute(FILTER_APPLIED) != null) {
        chain.doFilter(request, response);
        return;
    }
    request.setAttribute(FILTER_APPLIED, Boolean.TRUE);
    if (this.forceEagerSessionCreation) {
        HttpSession session = request.getSession();
        if (this.logger.isDebugEnabled() && session.isNew()) {
            this.logger.debug(LogMessage.format("Created session %s eagerly", session.getId()));
        }
    }
    HttpRequestResponseHolder holder = new HttpRequestResponseHolder(request, response);
    SecurityContext contextBeforeChainExecution = this.repo.loadContext(holder);
    try {
        SecurityContextHolder.setContext(contextBeforeChainExecution);
        if (contextBeforeChainExecution.getAuthentication() == null) {
            logger.debug("Set SecurityContextHolder to empty SecurityContext");
        } else {
            if (this.logger.isDebugEnabled()) {
                this.logger.debug(LogMessage.format("Set SecurityContextHolder to %s", contextBeforeChainExecution));
            }
        }
        chain.doFilter(holder.getRequest(), holder.getResponse());
    } finally {
        SecurityContext contextAfterChainExecution = SecurityContextHolder.getContext();
        // Crucial removal of SecurityContextHolder contents before anything else.
        SecurityContextHolder.clearContext();
        this.repo.saveContext(contextAfterChainExecution, holder.getRequest(), holder.getResponse());
        request.removeAttribute(FILTER_APPLIED);
        this.logger.debug("Cleared SecurityContextHolder to complete request");
    }
}
Also used : HttpSession(jakarta.servlet.http.HttpSession) SecurityContext(org.springframework.security.core.context.SecurityContext)

Example 95 with HttpSession

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

the class AbstractAuthenticationProcessingFilterTests method testNormalOperationWithRequestMatcherAndAuthenticationManager.

@Test
public void testNormalOperationWithRequestMatcherAndAuthenticationManager() throws Exception {
    // Setup our HTTP request
    MockHttpServletRequest request = createMockAuthenticationRequest();
    request.setServletPath("/j_eradicate_corona_virus");
    request.setRequestURI("/mycontext/j_eradicate_corona_virus");
    HttpSession sessionPreAuth = request.getSession();
    // Setup our filter configuration
    MockFilterConfig config = new MockFilterConfig(null, null);
    // Setup our expectation that the filter chain will not be invoked, as we redirect
    // to defaultTargetUrl
    MockFilterChain chain = new MockFilterChain(false);
    MockHttpServletResponse response = new MockHttpServletResponse();
    // Setup our test object, to grant access
    MockAuthenticationFilter filter = new MockAuthenticationFilter(new AntPathRequestMatcher("/j_eradicate_corona_virus"), mock(AuthenticationManager.class));
    filter.setSessionAuthenticationStrategy(mock(SessionAuthenticationStrategy.class));
    filter.setAuthenticationSuccessHandler(this.successHandler);
    filter.setAuthenticationFailureHandler(this.failureHandler);
    filter.afterPropertiesSet();
    // Test
    filter.doFilter(request, response, chain);
    assertThat(response.getRedirectedUrl()).isEqualTo("/mycontext/logged_in.jsp");
    assertThat(SecurityContextHolder.getContext().getAuthentication()).isNotNull();
    assertThat(SecurityContextHolder.getContext().getAuthentication().getPrincipal().toString()).isEqualTo("test");
    // Should still have the same session
    assertThat(request.getSession()).isEqualTo(sessionPreAuth);
}
Also used : AuthenticationManager(org.springframework.security.authentication.AuthenticationManager) SessionAuthenticationStrategy(org.springframework.security.web.authentication.session.SessionAuthenticationStrategy) MockHttpServletRequest(org.springframework.mock.web.MockHttpServletRequest) HttpSession(jakarta.servlet.http.HttpSession) AntPathRequestMatcher(org.springframework.security.web.util.matcher.AntPathRequestMatcher) MockHttpServletResponse(org.springframework.mock.web.MockHttpServletResponse) MockFilterConfig(org.springframework.mock.web.MockFilterConfig) Test(org.junit.jupiter.api.Test)

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