Search in sources :

Example 71 with HttpServletResponse

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

the class Response method setResponse.

/**
 * Set a wrapped HttpServletResponse to pass to the application. Components
 * wishing to wrap the response should obtain the response via
 * {@link #getResponse()}, wrap it and then call this method with the
 * wrapped response.
 *
 * @param applicationResponse The wrapped response to pass to the
 *        application
 */
public void setResponse(HttpServletResponse applicationResponse) {
    // Check the wrapper wraps this request
    ServletResponse r = applicationResponse;
    while (r instanceof HttpServletResponseWrapper) {
        r = ((HttpServletResponseWrapper) r).getResponse();
    }
    if (r != facade) {
        throw new IllegalArgumentException(sm.getString("response.illegalWrap"));
    }
    this.applicationResponse = applicationResponse;
}
Also used : ServletResponse(jakarta.servlet.ServletResponse) HttpServletResponse(jakarta.servlet.http.HttpServletResponse) HttpServletResponseWrapper(jakarta.servlet.http.HttpServletResponseWrapper)

Example 72 with HttpServletResponse

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

the class AsyncContextImpl method setErrorState.

public void setErrorState(Throwable t, boolean fireOnError) {
    if (t != null) {
        request.setAttribute(RequestDispatcher.ERROR_EXCEPTION, t);
    }
    request.getCoyoteRequest().action(ActionCode.ASYNC_ERROR, null);
    if (fireOnError) {
        if (log.isDebugEnabled()) {
            log.debug(sm.getString("asyncContextImpl.fireOnError"));
        }
        AsyncEvent errorEvent = new AsyncEvent(event.getAsyncContext(), event.getSuppliedRequest(), event.getSuppliedResponse(), t);
        List<AsyncListenerWrapper> listenersCopy = new ArrayList<>(listeners);
        for (AsyncListenerWrapper listener : listenersCopy) {
            try {
                listener.fireOnError(errorEvent);
            } catch (Throwable t2) {
                ExceptionUtils.handleThrowable(t2);
                log.warn(sm.getString("asyncContextImpl.onErrorError", listener.getClass().getName()), t2);
            }
        }
    }
    AtomicBoolean result = new AtomicBoolean();
    request.getCoyoteRequest().action(ActionCode.ASYNC_IS_ERROR, result);
    if (result.get()) {
        // No listener called dispatch() or complete(). This is an error.
        // SRV.2.3.3.3 (search for "error dispatch")
        // Take a local copy to avoid threading issues if another thread
        // clears this (can happen during error handling with non-container
        // threads)
        ServletResponse servletResponse = this.servletResponse;
        if (servletResponse instanceof HttpServletResponse) {
            ((HttpServletResponse) servletResponse).setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        }
        Host host = (Host) context.getParent();
        Valve stdHostValve = host.getPipeline().getBasic();
        if (stdHostValve instanceof StandardHostValve) {
            ((StandardHostValve) stdHostValve).throwable(request, request.getResponse(), t);
        }
        request.getCoyoteRequest().action(ActionCode.ASYNC_IS_ERROR, result);
        if (result.get()) {
            // Still in the error state. The error page did not call
            // complete() or dispatch(). Complete the async processing.
            complete();
        }
    }
}
Also used : AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) ServletResponse(jakarta.servlet.ServletResponse) HttpServletResponse(jakarta.servlet.http.HttpServletResponse) ArrayList(java.util.ArrayList) HttpServletResponse(jakarta.servlet.http.HttpServletResponse) Valve(org.apache.catalina.Valve) Host(org.apache.catalina.Host) AsyncEvent(jakarta.servlet.AsyncEvent)

Example 73 with HttpServletResponse

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

the class ServletOAuth2AuthorizedClientExchangeFilterFunctionITests method setUp.

@BeforeEach
public void setUp() throws Exception {
    this.clientRegistrationRepository = mock(ClientRegistrationRepository.class);
    final OAuth2AuthorizedClientRepository delegate = new AuthenticatedPrincipalOAuth2AuthorizedClientRepository(new InMemoryOAuth2AuthorizedClientService(this.clientRegistrationRepository));
    this.authorizedClientRepository = spy(new OAuth2AuthorizedClientRepository() {

        @Override
        public <T extends OAuth2AuthorizedClient> T loadAuthorizedClient(String clientRegistrationId, Authentication principal, HttpServletRequest request) {
            return delegate.loadAuthorizedClient(clientRegistrationId, principal, request);
        }

        @Override
        public void saveAuthorizedClient(OAuth2AuthorizedClient authorizedClient, Authentication principal, HttpServletRequest request, HttpServletResponse response) {
            delegate.saveAuthorizedClient(authorizedClient, principal, request, response);
        }

        @Override
        public void removeAuthorizedClient(String clientRegistrationId, Authentication principal, HttpServletRequest request, HttpServletResponse response) {
            delegate.removeAuthorizedClient(clientRegistrationId, principal, request, response);
        }
    });
    this.authorizedClientFilter = new ServletOAuth2AuthorizedClientExchangeFilterFunction(this.clientRegistrationRepository, this.authorizedClientRepository);
    this.server = new MockWebServer();
    this.server.start();
    this.serverUrl = this.server.url("/").toString();
    this.webClient = WebClient.builder().apply(this.authorizedClientFilter.oauth2Configuration()).build();
    this.authentication = new TestingAuthenticationToken("principal", "password");
    SecurityContextHolder.getContext().setAuthentication(this.authentication);
    this.request = new MockHttpServletRequest();
    this.response = new MockHttpServletResponse();
    RequestContextHolder.setRequestAttributes(new ServletRequestAttributes(this.request, this.response));
}
Also used : MockHttpServletRequest(org.springframework.mock.web.MockHttpServletRequest) InMemoryOAuth2AuthorizedClientService(org.springframework.security.oauth2.client.InMemoryOAuth2AuthorizedClientService) ServletRequestAttributes(org.springframework.web.context.request.ServletRequestAttributes) ClientRegistrationRepository(org.springframework.security.oauth2.client.registration.ClientRegistrationRepository) MockHttpServletResponse(org.springframework.mock.web.MockHttpServletResponse) HttpServletResponse(jakarta.servlet.http.HttpServletResponse) TestingAuthenticationToken(org.springframework.security.authentication.TestingAuthenticationToken) AuthenticatedPrincipalOAuth2AuthorizedClientRepository(org.springframework.security.oauth2.client.web.AuthenticatedPrincipalOAuth2AuthorizedClientRepository) OAuth2AuthorizedClientRepository(org.springframework.security.oauth2.client.web.OAuth2AuthorizedClientRepository) HttpServletRequest(jakarta.servlet.http.HttpServletRequest) MockHttpServletRequest(org.springframework.mock.web.MockHttpServletRequest) Authentication(org.springframework.security.core.Authentication) AuthenticatedPrincipalOAuth2AuthorizedClientRepository(org.springframework.security.oauth2.client.web.AuthenticatedPrincipalOAuth2AuthorizedClientRepository) MockWebServer(okhttp3.mockwebserver.MockWebServer) OAuth2AuthorizedClient(org.springframework.security.oauth2.client.OAuth2AuthorizedClient) MockHttpServletResponse(org.springframework.mock.web.MockHttpServletResponse) BeforeEach(org.junit.jupiter.api.BeforeEach)

Example 74 with HttpServletResponse

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

the class AbstractRememberMeServicesTests method cookieTheftExceptionShouldBeRethrown.

@Test
public void cookieTheftExceptionShouldBeRethrown() {
    MockRememberMeServices services = new MockRememberMeServices(this.uds) {

        @Override
        protected UserDetails processAutoLoginCookie(String[] cookieTokens, HttpServletRequest request, HttpServletResponse response) {
            throw new CookieTheftException("Pretending cookie was stolen");
        }
    };
    MockHttpServletRequest request = new MockHttpServletRequest();
    request.setCookies(createLoginCookie("cookie:1:2"));
    MockHttpServletResponse response = new MockHttpServletResponse();
    assertThatExceptionOfType(CookieTheftException.class).isThrownBy(() -> services.autoLogin(request, response));
}
Also used : HttpServletRequest(jakarta.servlet.http.HttpServletRequest) MockHttpServletRequest(org.springframework.mock.web.MockHttpServletRequest) MockHttpServletRequest(org.springframework.mock.web.MockHttpServletRequest) MockHttpServletResponse(org.springframework.mock.web.MockHttpServletResponse) HttpServletResponse(jakarta.servlet.http.HttpServletResponse) MockHttpServletResponse(org.springframework.mock.web.MockHttpServletResponse) Test(org.junit.jupiter.api.Test)

Example 75 with HttpServletResponse

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

the class RememberMeAuthenticationFilterTests method onUnsuccessfulLoginIsCalledWhenProviderRejectsAuth.

@Test
public void onUnsuccessfulLoginIsCalledWhenProviderRejectsAuth() throws Exception {
    final Authentication failedAuth = new TestingAuthenticationToken("failed", "");
    AuthenticationManager am = mock(AuthenticationManager.class);
    given(am.authenticate(any(Authentication.class))).willThrow(new BadCredentialsException(""));
    RememberMeAuthenticationFilter filter = new RememberMeAuthenticationFilter(am, new MockRememberMeServices(this.remembered)) {

        @Override
        protected void onUnsuccessfulAuthentication(HttpServletRequest request, HttpServletResponse response, AuthenticationException failed) {
            super.onUnsuccessfulAuthentication(request, response, failed);
            SecurityContextHolder.getContext().setAuthentication(failedAuth);
        }
    };
    filter.setApplicationEventPublisher(mock(ApplicationEventPublisher.class));
    filter.afterPropertiesSet();
    MockHttpServletRequest request = new MockHttpServletRequest();
    FilterChain fc = mock(FilterChain.class);
    request.setRequestURI("x");
    filter.doFilter(request, new MockHttpServletResponse(), fc);
    assertThat(SecurityContextHolder.getContext().getAuthentication()).isSameAs(failedAuth);
    verify(fc).doFilter(any(HttpServletRequest.class), any(HttpServletResponse.class));
}
Also used : AuthenticationException(org.springframework.security.core.AuthenticationException) MockHttpServletRequest(org.springframework.mock.web.MockHttpServletRequest) FilterChain(jakarta.servlet.FilterChain) MockHttpServletResponse(org.springframework.mock.web.MockHttpServletResponse) HttpServletResponse(jakarta.servlet.http.HttpServletResponse) TestingAuthenticationToken(org.springframework.security.authentication.TestingAuthenticationToken) BadCredentialsException(org.springframework.security.authentication.BadCredentialsException) AuthenticationManager(org.springframework.security.authentication.AuthenticationManager) HttpServletRequest(jakarta.servlet.http.HttpServletRequest) MockHttpServletRequest(org.springframework.mock.web.MockHttpServletRequest) Authentication(org.springframework.security.core.Authentication) ApplicationEventPublisher(org.springframework.context.ApplicationEventPublisher) MockHttpServletResponse(org.springframework.mock.web.MockHttpServletResponse) Test(org.junit.jupiter.api.Test)

Aggregations

HttpServletResponse (jakarta.servlet.http.HttpServletResponse)118 HttpServletRequest (jakarta.servlet.http.HttpServletRequest)76 Test (org.junit.jupiter.api.Test)47 MockHttpServletResponse (org.springframework.web.testfixture.servlet.MockHttpServletResponse)34 MockHttpServletRequest (org.springframework.web.testfixture.servlet.MockHttpServletRequest)31 FilterChain (jakarta.servlet.FilterChain)22 Assertions.assertThat (org.assertj.core.api.Assertions.assertThat)18 MockHttpServletRequest (org.springframework.mock.web.MockHttpServletRequest)16 MockHttpServletResponse (org.springframework.mock.web.MockHttpServletResponse)15 ServletException (jakarta.servlet.ServletException)14 StandardCharsets (java.nio.charset.StandardCharsets)14 HttpServlet (jakarta.servlet.http.HttpServlet)13 IOException (java.io.IOException)12 HashMap (java.util.HashMap)12 TomcatBaseTest (org.apache.catalina.startup.TomcatBaseTest)10 Test (org.junit.Test)10 Authentication (org.springframework.security.core.Authentication)10 FileCopyUtils (org.springframework.util.FileCopyUtils)9 BeforeEach (org.junit.jupiter.api.BeforeEach)8 Collections (java.util.Collections)7