Search in sources :

Example 1 with ServletResponse

use of jakarta.servlet.ServletResponse in project atmosphere by Atmosphere.

the class SSEAtmosphereInterceptorTest method testDataWriter.

@Test
public void testDataWriter() throws Exception {
    final ByteArrayOutputStream baos = new ByteArrayOutputStream();
    ServletResponse resp = Mockito.mock(HttpServletResponse.class);
    Mockito.when(resp.getOutputStream()).thenReturn(new ServletOutputStream() {

        @Override
        public boolean isReady() {
            return false;
        }

        @Override
        public void setWriteListener(WriteListener writeListener) {
        }

        @Override
        public void write(int b) throws IOException {
            baos.write(b);
        }

        @Override
        public void write(byte[] b) throws IOException {
            baos.write(b);
        }

        @Override
        public void write(byte[] b, int off, int len) throws IOException {
            baos.write(b, off, len);
        }
    });
    AtmosphereRequest request = AtmosphereRequestImpl.newInstance();
    request.header(HeaderConfig.X_ATMOSPHERE_TRANSPORT, "SSE");
    AtmosphereResponse response = AtmosphereResponseImpl.newInstance(request);
    response.request(request);
    response.setResponse(resp);
    AtmosphereResourceImpl resource = new AtmosphereResourceImpl();
    resource.initialize(framework.getAtmosphereConfig(), framework.getBroadcasterFactory().get(), request, response, Mockito.mock(AsyncSupport.class), null);
    resource.suspend();
    SSEAtmosphereInterceptor interceptor = new SSEAtmosphereInterceptor();
    interceptor.configure(config);
    interceptor.inspect(resource);
    // no newline
    response.write("Good Morning".getBytes());
    assertEquals(baos.toString(), "data:Good Morning\r\n\r\n");
    baos.reset();
    // \n
    response.write("Hello World!\nHave a nice day!".getBytes());
    assertEquals(baos.toString(), "data:Hello World!\r\ndata:Have a nice day!\r\n\r\n");
    baos.reset();
    // \r
    response.write("Hello World!\rHave a nice day!".getBytes());
    assertEquals(baos.toString(), "data:Hello World!\r\ndata:Have a nice day!\r\n\r\n");
    baos.reset();
    // \r\n
    response.write("Hello World!\r\nHave a nice day!".getBytes());
    assertEquals(baos.toString(), "data:Hello World!\r\ndata:Have a nice day!\r\n\r\n");
}
Also used : ServletResponse(jakarta.servlet.ServletResponse) HttpServletResponse(jakarta.servlet.http.HttpServletResponse) AtmosphereResponse(org.atmosphere.cpr.AtmosphereResponse) ServletOutputStream(jakarta.servlet.ServletOutputStream) AsyncSupport(org.atmosphere.cpr.AsyncSupport) ByteArrayOutputStream(java.io.ByteArrayOutputStream) IOException(java.io.IOException) AtmosphereRequest(org.atmosphere.cpr.AtmosphereRequest) AtmosphereResourceImpl(org.atmosphere.cpr.AtmosphereResourceImpl) WriteListener(jakarta.servlet.WriteListener) Test(org.testng.annotations.Test)

Example 2 with ServletResponse

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

the class Saml2WebSsoAuthenticationRequestFilterTests method setup.

@BeforeEach
public void setup() {
    this.filter = new Saml2WebSsoAuthenticationRequestFilter(this.resolver, this.factory);
    this.request = new MockHttpServletRequest();
    this.response = new MockHttpServletResponse();
    this.request.setPathInfo("/saml2/authenticate/registration-id");
    this.filterChain = new MockFilterChain() {

        @Override
        public void doFilter(ServletRequest request, ServletResponse response) {
            ((HttpServletResponse) response).setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        }
    };
    this.rpBuilder = RelyingPartyRegistration.withRegistrationId("registration-id").providerDetails((c) -> c.entityId("idp-entity-id")).providerDetails((c) -> c.webSsoUrl(IDP_SSO_URL)).assertionConsumerServiceUrlTemplate("template").credentials((c) -> c.add(TestSaml2X509Credentials.assertingPartyPrivateCredential()));
    this.filter.setAuthenticationRequestRepository(this.authenticationRequestRepository);
}
Also used : Saml2AuthenticationRequestRepository(org.springframework.security.saml2.provider.service.web.Saml2AuthenticationRequestRepository) ArgumentMatchers.any(org.mockito.ArgumentMatchers.any) BeforeEach(org.junit.jupiter.api.BeforeEach) MockFilterChain(org.springframework.mock.web.MockFilterChain) ArgumentMatchers.eq(org.mockito.ArgumentMatchers.eq) RelyingPartyRegistrationRepository(org.springframework.security.saml2.provider.service.registration.RelyingPartyRegistrationRepository) Assertions.assertThat(org.assertj.core.api.Assertions.assertThat) Saml2AuthenticationRequestResolver(org.springframework.security.saml2.provider.service.web.authentication.Saml2AuthenticationRequestResolver) DefaultSaml2AuthenticationRequestContextResolver(org.springframework.security.saml2.provider.service.web.DefaultSaml2AuthenticationRequestContextResolver) ServletException(jakarta.servlet.ServletException) MockHttpServletResponse(org.springframework.mock.web.MockHttpServletResponse) RelyingPartyRegistration(org.springframework.security.saml2.provider.service.registration.RelyingPartyRegistration) HtmlUtils(org.springframework.web.util.HtmlUtils) Saml2MessageBinding(org.springframework.security.saml2.provider.service.registration.Saml2MessageBinding) Mockito.verifyNoInteractions(org.mockito.Mockito.verifyNoInteractions) Saml2AuthenticationRequestContextResolver(org.springframework.security.saml2.provider.service.web.Saml2AuthenticationRequestContextResolver) BDDMockito.given(org.mockito.BDDMockito.given) AbstractSaml2AuthenticationRequest(org.springframework.security.saml2.provider.service.authentication.AbstractSaml2AuthenticationRequest) Saml2AuthenticationRequestContext(org.springframework.security.saml2.provider.service.authentication.Saml2AuthenticationRequestContext) Saml2PostAuthenticationRequest(org.springframework.security.saml2.provider.service.authentication.Saml2PostAuthenticationRequest) Saml2RedirectAuthenticationRequest(org.springframework.security.saml2.provider.service.authentication.Saml2RedirectAuthenticationRequest) DefaultRelyingPartyRegistrationResolver(org.springframework.security.saml2.provider.service.web.DefaultRelyingPartyRegistrationResolver) Saml2AuthenticationRequestFactory(org.springframework.security.saml2.provider.service.authentication.Saml2AuthenticationRequestFactory) ServletRequest(jakarta.servlet.ServletRequest) RelyingPartyRegistrationResolver(org.springframework.security.saml2.provider.service.web.RelyingPartyRegistrationResolver) IOException(java.io.IOException) MockHttpServletRequest(org.springframework.mock.web.MockHttpServletRequest) RequestMatcher(org.springframework.security.web.util.matcher.RequestMatcher) StandardCharsets(java.nio.charset.StandardCharsets) Mockito.verify(org.mockito.Mockito.verify) Test(org.junit.jupiter.api.Test) TestSaml2X509Credentials(org.springframework.security.saml2.credentials.TestSaml2X509Credentials) ServletResponse(jakarta.servlet.ServletResponse) Assertions.assertThatIllegalArgumentException(org.assertj.core.api.Assertions.assertThatIllegalArgumentException) UriUtils(org.springframework.web.util.UriUtils) HttpServletResponse(jakarta.servlet.http.HttpServletResponse) TestSaml2AuthenticationRequestContexts(org.springframework.security.saml2.provider.service.authentication.TestSaml2AuthenticationRequestContexts) TestRelyingPartyRegistrations(org.springframework.security.saml2.provider.service.registration.TestRelyingPartyRegistrations) AntPathRequestMatcher(org.springframework.security.web.util.matcher.AntPathRequestMatcher) Mockito.mock(org.mockito.Mockito.mock) ServletRequest(jakarta.servlet.ServletRequest) MockHttpServletRequest(org.springframework.mock.web.MockHttpServletRequest) MockHttpServletResponse(org.springframework.mock.web.MockHttpServletResponse) ServletResponse(jakarta.servlet.ServletResponse) HttpServletResponse(jakarta.servlet.http.HttpServletResponse) MockHttpServletRequest(org.springframework.mock.web.MockHttpServletRequest) MockFilterChain(org.springframework.mock.web.MockFilterChain) MockHttpServletResponse(org.springframework.mock.web.MockHttpServletResponse) BeforeEach(org.junit.jupiter.api.BeforeEach)

Example 3 with ServletResponse

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

the class GrantedAuthorityDefaultsXmlTests method doFilterIsUserInRole.

// SEC-2926
@Test
public void doFilterIsUserInRole() throws Exception {
    SecurityContext context = SecurityContextHolder.getContext();
    this.request.getSession().setAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY, context);
    this.chain = new MockFilterChain() {

        @Override
        public void doFilter(ServletRequest request, ServletResponse response) throws IOException, ServletException {
            HttpServletRequest httpRequest = (HttpServletRequest) request;
            assertThat(httpRequest.isUserInRole("USER")).isTrue();
            assertThat(httpRequest.isUserInRole("INVALID")).isFalse();
            super.doFilter(request, response);
        }
    };
    this.springSecurityFilterChain.doFilter(this.request, this.response, this.chain);
    assertThat(this.chain.getRequest()).isNotNull();
}
Also used : ServletException(jakarta.servlet.ServletException) HttpServletRequest(jakarta.servlet.http.HttpServletRequest) MockHttpServletRequest(org.springframework.mock.web.MockHttpServletRequest) ServletRequest(jakarta.servlet.ServletRequest) HttpServletRequest(jakarta.servlet.http.HttpServletRequest) MockHttpServletRequest(org.springframework.mock.web.MockHttpServletRequest) MockHttpServletResponse(org.springframework.mock.web.MockHttpServletResponse) ServletResponse(jakarta.servlet.ServletResponse) HttpServletResponse(jakarta.servlet.http.HttpServletResponse) SecurityContext(org.springframework.security.core.context.SecurityContext) IOException(java.io.IOException) MockFilterChain(org.springframework.mock.web.MockFilterChain) Test(org.junit.jupiter.api.Test)

Example 4 with ServletResponse

use of jakarta.servlet.ServletResponse in project tomcat by apache.

the class ApplicationFilterChain method doFilter.

// ---------------------------------------------------- FilterChain Methods
/**
 * Invoke the next filter in this chain, passing the specified request
 * and response.  If there are no more filters in this chain, invoke
 * the <code>service()</code> method of the servlet itself.
 *
 * @param request The servlet request we are processing
 * @param response The servlet response we are creating
 *
 * @exception IOException if an input/output error occurs
 * @exception ServletException if a servlet exception occurs
 */
@Override
public void doFilter(ServletRequest request, ServletResponse response) throws IOException, ServletException {
    if (Globals.IS_SECURITY_ENABLED) {
        final ServletRequest req = request;
        final ServletResponse res = response;
        try {
            java.security.AccessController.doPrivileged((java.security.PrivilegedExceptionAction<Void>) () -> {
                internalDoFilter(req, res);
                return null;
            });
        } catch (PrivilegedActionException pe) {
            Exception e = pe.getException();
            if (e instanceof ServletException) {
                throw (ServletException) e;
            } else if (e instanceof IOException) {
                throw (IOException) e;
            } else if (e instanceof RuntimeException) {
                throw (RuntimeException) e;
            } else {
                throw new ServletException(e.getMessage(), e);
            }
        }
    } else {
        internalDoFilter(request, response);
    }
}
Also used : ServletException(jakarta.servlet.ServletException) ServletRequest(jakarta.servlet.ServletRequest) HttpServletRequest(jakarta.servlet.http.HttpServletRequest) ServletResponse(jakarta.servlet.ServletResponse) HttpServletResponse(jakarta.servlet.http.HttpServletResponse) PrivilegedActionException(java.security.PrivilegedActionException) IOException(java.io.IOException) PrivilegedActionException(java.security.PrivilegedActionException) IOException(java.io.IOException) ServletException(jakarta.servlet.ServletException)

Example 5 with ServletResponse

use of jakarta.servlet.ServletResponse in project tomcat by apache.

the class ApplicationFilterChain method internalDoFilter.

private void internalDoFilter(ServletRequest request, ServletResponse response) throws IOException, ServletException {
    // Call the next filter if there is one
    if (pos < n) {
        ApplicationFilterConfig filterConfig = filters[pos++];
        try {
            Filter filter = filterConfig.getFilter();
            if (request.isAsyncSupported() && "false".equalsIgnoreCase(filterConfig.getFilterDef().getAsyncSupported())) {
                request.setAttribute(Globals.ASYNC_SUPPORTED_ATTR, Boolean.FALSE);
            }
            if (Globals.IS_SECURITY_ENABLED) {
                final ServletRequest req = request;
                final ServletResponse res = response;
                Principal principal = ((HttpServletRequest) req).getUserPrincipal();
                Object[] args = new Object[] { req, res, this };
                SecurityUtil.doAsPrivilege("doFilter", filter, classType, args, principal);
            } else {
                filter.doFilter(request, response, this);
            }
        } catch (IOException | ServletException | RuntimeException e) {
            throw e;
        } catch (Throwable e) {
            e = ExceptionUtils.unwrapInvocationTargetException(e);
            ExceptionUtils.handleThrowable(e);
            throw new ServletException(sm.getString("filterChain.filter"), e);
        }
        return;
    }
    // We fell off the end of the chain -- call the servlet instance
    try {
        if (dispatcherWrapsSameObject) {
            lastServicedRequest.set(request);
            lastServicedResponse.set(response);
        }
        if (request.isAsyncSupported() && !servletSupportsAsync) {
            request.setAttribute(Globals.ASYNC_SUPPORTED_ATTR, Boolean.FALSE);
        }
        // Use potentially wrapped request from this point
        if ((request instanceof HttpServletRequest) && (response instanceof HttpServletResponse) && Globals.IS_SECURITY_ENABLED) {
            final ServletRequest req = request;
            final ServletResponse res = response;
            Principal principal = ((HttpServletRequest) req).getUserPrincipal();
            Object[] args = new Object[] { req, res };
            SecurityUtil.doAsPrivilege("service", servlet, classTypeUsedInService, args, principal);
        } else {
            servlet.service(request, response);
        }
    } catch (IOException | ServletException | RuntimeException e) {
        throw e;
    } catch (Throwable e) {
        e = ExceptionUtils.unwrapInvocationTargetException(e);
        ExceptionUtils.handleThrowable(e);
        throw new ServletException(sm.getString("filterChain.servlet"), e);
    } finally {
        if (dispatcherWrapsSameObject) {
            lastServicedRequest.set(null);
            lastServicedResponse.set(null);
        }
    }
}
Also used : ServletRequest(jakarta.servlet.ServletRequest) HttpServletRequest(jakarta.servlet.http.HttpServletRequest) ServletResponse(jakarta.servlet.ServletResponse) HttpServletResponse(jakarta.servlet.http.HttpServletResponse) HttpServletResponse(jakarta.servlet.http.HttpServletResponse) IOException(java.io.IOException) HttpServletRequest(jakarta.servlet.http.HttpServletRequest) ServletException(jakarta.servlet.ServletException) Filter(jakarta.servlet.Filter) Principal(java.security.Principal)

Aggregations

ServletResponse (jakarta.servlet.ServletResponse)21 HttpServletResponse (jakarta.servlet.http.HttpServletResponse)17 ServletRequest (jakarta.servlet.ServletRequest)13 HttpServletRequest (jakarta.servlet.http.HttpServletRequest)10 ServletException (jakarta.servlet.ServletException)9 IOException (java.io.IOException)8 Test (org.junit.jupiter.api.Test)5 ServletResponseWrapper (jakarta.servlet.ServletResponseWrapper)4 MockFilterChain (org.springframework.mock.web.MockFilterChain)4 MockHttpServletRequest (org.springframework.mock.web.MockHttpServletRequest)4 MockHttpServletResponse (org.springframework.mock.web.MockHttpServletResponse)4 MockHttpServletRequest (org.springframework.web.testfixture.servlet.MockHttpServletRequest)4 MockHttpServletResponse (org.springframework.web.testfixture.servlet.MockHttpServletResponse)4 Response (org.apache.catalina.connector.Response)3 AsyncEvent (jakarta.servlet.AsyncEvent)2 ServletOutputStream (jakarta.servlet.ServletOutputStream)2 HashMap (java.util.HashMap)2 Properties (java.util.Properties)2 Context (org.apache.catalina.Context)2 ResponseFacade (org.apache.catalina.connector.ResponseFacade)2