Search in sources :

Example 96 with FilterChain

use of javax.servlet.FilterChain in project wicket by apache.

the class WicketFilterTest method ignorePaths.

/**
 * <a href="https://issues.apache.org/jira/browse/WICKET-3750">WICKET-3750</a>
 *
 * @throws Exception
 */
@Test
public void ignorePaths() throws Exception {
    application = spy(new MockApplication());
    WicketFilter filter = new WicketFilter();
    filter.init(new FilterTestingConfig());
    HttpServletRequest request = mock(HttpServletRequest.class);
    when(request.getLocale()).thenReturn(new Locale("bg", "BG"));
    when(request.getRequestURI()).thenReturn("/contextPath/js/bla.js").thenReturn("/contextPath/css/bla.css").thenReturn("/contextPath/images/bla.img").thenReturn("/contextPath/servlet/wicket/bookmarkable/" + DummyHomePage.class.getName());
    when(request.getContextPath()).thenReturn("/contextPath");
    when(request.getMethod()).thenReturn("POST");
    HttpServletResponse response = mock(HttpServletResponse.class);
    when(response.encodeRedirectURL(Matchers.anyString())).thenAnswer(new Answer<String>() {

        @Override
        public String answer(InvocationOnMock invocation) throws Throwable {
            return (String) invocation.getArguments()[0];
        }
    });
    FilterChain chain = mock(FilterChain.class);
    // execute 3 requests - 1 for bla.js, 1 for bla.css and 1 for bla.img
    for (int i = 0; i < 3; i++) {
        boolean isProcessed = filter.processRequest(request, response, chain);
        assertFalse(isProcessed);
        verify(application, Mockito.never()).newWebRequest(Matchers.eq(request), Matchers.anyString());
        verify(application, Mockito.never()).newWebResponse(Matchers.any(WebRequest.class), Matchers.eq(response));
        verify(chain, Mockito.times(i + 1)).doFilter(request, response);
    }
    // execute the request to /something/real
    boolean isProcessed = filter.processRequest(request, response, chain);
    assertTrue(isProcessed);
    verify(application).newWebRequest(Matchers.eq(request), Matchers.anyString());
    verify(application).newWebResponse(Matchers.any(WebRequest.class), Matchers.eq(response));
    // the request is processed so the chain is not executed
    verify(chain, Mockito.times(3)).doFilter(request, response);
}
Also used : Locale(java.util.Locale) MockApplication(org.apache.wicket.mock.MockApplication) FilterChain(javax.servlet.FilterChain) MockHttpServletResponse(org.apache.wicket.protocol.http.mock.MockHttpServletResponse) HttpServletResponse(javax.servlet.http.HttpServletResponse) HttpServletRequest(javax.servlet.http.HttpServletRequest) MockHttpServletRequest(org.apache.wicket.protocol.http.mock.MockHttpServletRequest) WebRequest(org.apache.wicket.request.http.WebRequest) InvocationOnMock(org.mockito.invocation.InvocationOnMock) Test(org.junit.Test)

Example 97 with FilterChain

use of javax.servlet.FilterChain in project wicket by apache.

the class WicketFilterTest method options.

@Test
public void options() throws IOException, ServletException, ParseException {
    try {
        application = new MockApplication();
        WicketFilter filter = new WicketFilter();
        filter.init(new FilterTestingConfig());
        ThreadContext.setApplication(application);
        final String failure = "Should never get here when an OPTIONS request is issued";
        IResource resource = new AbstractResource() {

            @Override
            protected ResourceResponse newResourceResponse(Attributes attributes) {
                fail(failure);
                return null;
            }
        };
        application.getSharedResources().add("foo.txt", resource);
        // check OPTIONS request is processed correctly
        MockHttpServletRequest request = new MockHttpServletRequest(application, null, null);
        request.setURL(request.getContextPath() + request.getServletPath() + "/wicket/resource/" + Application.class.getName() + "/foo.txt");
        // test that we do not care about case
        request.setMethod("OPtioNS");
        MockHttpServletResponse response = new MockHttpServletResponse(request);
        filter.doFilter(request, response, new FilterChain() {

            @Override
            public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse) throws IOException, ServletException {
            }
        });
        assertEquals(HttpServletResponse.SC_OK, response.getStatus());
        assertEquals("0", response.getHeader("Content-Length"));
        assertFalse(Strings.isEmpty(response.getHeader("Allow")));
        assertTrue(response.getHeader("Allow").toUpperCase().contains("GET"));
        assertTrue(response.getHeader("Allow").toUpperCase().contains("POST"));
        // try with a GET request to make sure we fail correctly
        request = new MockHttpServletRequest(application, null, null);
        request.setURL(request.getContextPath() + request.getServletPath() + "/wicket/resource/" + Application.class.getName() + "/foo.txt");
        response = new MockHttpServletResponse(request);
        try {
            filter.doFilter(request, response, new FilterChain() {

                @Override
                public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse) throws IOException, ServletException {
                }
            });
        } catch (AssertionError e) {
            assertTrue(failure.equals(e.getMessage()));
        }
    } finally {
        ThreadContext.detach();
    }
}
Also used : HttpServletRequest(javax.servlet.http.HttpServletRequest) ServletRequest(javax.servlet.ServletRequest) MockHttpServletRequest(org.apache.wicket.protocol.http.mock.MockHttpServletRequest) MockHttpServletResponse(org.apache.wicket.protocol.http.mock.MockHttpServletResponse) HttpServletResponse(javax.servlet.http.HttpServletResponse) ServletResponse(javax.servlet.ServletResponse) MockApplication(org.apache.wicket.mock.MockApplication) MockHttpServletRequest(org.apache.wicket.protocol.http.mock.MockHttpServletRequest) FilterChain(javax.servlet.FilterChain) AbstractResource(org.apache.wicket.request.resource.AbstractResource) IOException(java.io.IOException) ServletException(javax.servlet.ServletException) MockApplication(org.apache.wicket.mock.MockApplication) Application(org.apache.wicket.Application) IResource(org.apache.wicket.request.resource.IResource) MockHttpServletResponse(org.apache.wicket.protocol.http.mock.MockHttpServletResponse) Test(org.junit.Test)

Example 98 with FilterChain

use of javax.servlet.FilterChain in project gravitee-management-rest-api by gravitee-io.

the class AuthenticationSuccessFilter method doFilter.

@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
    final HttpServletRequest req = (HttpServletRequest) servletRequest;
    final Optional<Cookie> optionalStringToken;
    if (req.getCookies() == null) {
        optionalStringToken = Optional.empty();
    } else {
        optionalStringToken = Arrays.stream(req.getCookies()).filter(cookie -> HttpHeaders.AUTHORIZATION.equals(cookie.getName())).filter(cookie -> cookie.getValue() != null && !cookie.getValue().isEmpty()).findAny();
    }
    final Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
    if (authentication != null && !optionalStringToken.isPresent()) {
        // JWT signer
        final Map<String, Object> claims = new HashMap<>();
        claims.put(Claims.ISSUER, jwtIssuer);
        final UserDetails userDetails = (UserDetails) authentication.getPrincipal();
        // Manage authorities, initialize it with dynamic permissions from the IDP
        Set<GrantedAuthority> authorities = new HashSet<>(userDetails.getAuthorities());
        // We must also load permissions from repository for configured management or portal role
        RoleEntity role = membershipService.getRole(MembershipReferenceType.MANAGEMENT, MembershipDefaultReferenceId.DEFAULT.toString(), userDetails.getUsername(), RoleScope.MANAGEMENT);
        if (role != null) {
            authorities.add(new SimpleGrantedAuthority(role.getScope().toString() + ':' + role.getName()));
        }
        role = membershipService.getRole(MembershipReferenceType.PORTAL, MembershipDefaultReferenceId.DEFAULT.toString(), userDetails.getUsername(), RoleScope.PORTAL);
        if (role != null) {
            authorities.add(new SimpleGrantedAuthority(role.getScope().toString() + ':' + role.getName()));
        }
        claims.put(Claims.PERMISSIONS, authorities);
        claims.put(Claims.SUBJECT, userDetails.getUsername());
        claims.put(Claims.EMAIL, userDetails.getEmail());
        claims.put(Claims.FIRSTNAME, userDetails.getFirstname());
        claims.put(Claims.LASTNAME, userDetails.getLastname());
        final JWTSigner.Options options = new JWTSigner.Options();
        options.setExpirySeconds(jwtExpireAfter);
        options.setIssuedAt(true);
        options.setJwtId(true);
        final Cookie bearerCookie = jwtCookieGenerator.generate("Bearer " + new JWTSigner(jwtSecret).sign(claims, options));
        ((HttpServletResponse) servletResponse).addCookie(bearerCookie);
    }
    filterChain.doFilter(servletRequest, servletResponse);
}
Also used : Cookie(javax.servlet.http.Cookie) JWTCookieGenerator(io.gravitee.management.security.cookies.JWTCookieGenerator) UserDetails(io.gravitee.management.idp.api.authentication.UserDetails) RoleScope(io.gravitee.repository.management.model.RoleScope) FilterChain(javax.servlet.FilterChain) ServletRequest(javax.servlet.ServletRequest) java.util(java.util) HttpHeaders(io.gravitee.common.http.HttpHeaders) RoleEntity(io.gravitee.management.model.RoleEntity) ServletException(javax.servlet.ServletException) MembershipDefaultReferenceId(io.gravitee.repository.management.model.MembershipDefaultReferenceId) HttpServletResponse(javax.servlet.http.HttpServletResponse) SimpleGrantedAuthority(org.springframework.security.core.authority.SimpleGrantedAuthority) IOException(java.io.IOException) GrantedAuthority(org.springframework.security.core.GrantedAuthority) HttpServletRequest(javax.servlet.http.HttpServletRequest) MembershipService(io.gravitee.management.service.MembershipService) ServletResponse(javax.servlet.ServletResponse) GenericFilterBean(org.springframework.web.filter.GenericFilterBean) JWTSigner(com.auth0.jwt.JWTSigner) Claims(io.gravitee.management.service.common.JWTHelper.Claims) MembershipReferenceType(io.gravitee.repository.management.model.MembershipReferenceType) Authentication(org.springframework.security.core.Authentication) SecurityContextHolder(org.springframework.security.core.context.SecurityContextHolder) Cookie(javax.servlet.http.Cookie) JWTSigner(com.auth0.jwt.JWTSigner) SimpleGrantedAuthority(org.springframework.security.core.authority.SimpleGrantedAuthority) GrantedAuthority(org.springframework.security.core.GrantedAuthority) HttpServletResponse(javax.servlet.http.HttpServletResponse) HttpServletRequest(javax.servlet.http.HttpServletRequest) RoleEntity(io.gravitee.management.model.RoleEntity) SimpleGrantedAuthority(org.springframework.security.core.authority.SimpleGrantedAuthority) UserDetails(io.gravitee.management.idp.api.authentication.UserDetails) Authentication(org.springframework.security.core.Authentication)

Example 99 with FilterChain

use of javax.servlet.FilterChain in project herd by FINRAOS.

the class RequestLoggingFilterTest method testDoFilterReadInputStreamFromFilterChainWithNoPayloadNoDebugLevel.

@Test
public void testDoFilterReadInputStreamFromFilterChainWithNoPayloadNoDebugLevel() throws Exception {
    // Turn on info logging which will disable the core functionality of the filter (i.e. no logging).
    setLogLevel(RequestLoggingFilter.class, LogLevel.INFO);
    FilterChain filterChain = new MockFilterChain() {

        public void doFilter(ServletRequest request, ServletResponse response) throws IOException, ServletException {
            String payload = IOUtils.toString(request.getInputStream());
            assertEquals("", payload);
        }
    };
    MockHttpServletRequest request = createServletRequest();
    request.setContent(null);
    // Run the filter.
    createFilter().doFilter(request, createServletResponse(), filterChain);
}
Also used : ServletRequest(javax.servlet.ServletRequest) MockHttpServletRequest(org.springframework.mock.web.MockHttpServletRequest) HttpServletRequest(javax.servlet.http.HttpServletRequest) MockHttpServletResponse(org.springframework.mock.web.MockHttpServletResponse) ServletResponse(javax.servlet.ServletResponse) MockHttpServletRequest(org.springframework.mock.web.MockHttpServletRequest) FilterChain(javax.servlet.FilterChain) MockFilterChain(org.springframework.mock.web.MockFilterChain) MockFilterChain(org.springframework.mock.web.MockFilterChain) Test(org.junit.Test)

Example 100 with FilterChain

use of javax.servlet.FilterChain in project herd by FINRAOS.

the class RequestLoggingFilterTest method testDoFilterReadInputStreamFromFilterChainWithNoPayload.

@Test
public void testDoFilterReadInputStreamFromFilterChainWithNoPayload() throws Exception {
    FilterChain filterChain = new MockFilterChain() {

        public void doFilter(ServletRequest request, ServletResponse response) throws IOException, ServletException {
            String payload = IOUtils.toString(request.getInputStream());
            assertEquals("", payload);
        }
    };
    MockHttpServletRequest request = createServletRequest();
    request.setContent(null);
    // Run the filter.
    createFilter().doFilter(request, createServletResponse(), filterChain);
}
Also used : ServletRequest(javax.servlet.ServletRequest) MockHttpServletRequest(org.springframework.mock.web.MockHttpServletRequest) HttpServletRequest(javax.servlet.http.HttpServletRequest) MockHttpServletResponse(org.springframework.mock.web.MockHttpServletResponse) ServletResponse(javax.servlet.ServletResponse) MockHttpServletRequest(org.springframework.mock.web.MockHttpServletRequest) FilterChain(javax.servlet.FilterChain) MockFilterChain(org.springframework.mock.web.MockFilterChain) MockFilterChain(org.springframework.mock.web.MockFilterChain) Test(org.junit.Test)

Aggregations

FilterChain (javax.servlet.FilterChain)418 HttpServletRequest (javax.servlet.http.HttpServletRequest)317 HttpServletResponse (javax.servlet.http.HttpServletResponse)269 Test (org.junit.Test)246 ServletResponse (javax.servlet.ServletResponse)135 ServletRequest (javax.servlet.ServletRequest)118 FilterConfig (javax.servlet.FilterConfig)80 Filter (javax.servlet.Filter)68 ServletException (javax.servlet.ServletException)54 IOException (java.io.IOException)48 MockHttpServletRequest (org.springframework.mock.web.MockHttpServletRequest)46 MockHttpServletResponse (org.springframework.mock.web.MockHttpServletResponse)46 Injector (com.google.inject.Injector)32 ServletTestUtils.newFakeHttpServletRequest (com.google.inject.servlet.ServletTestUtils.newFakeHttpServletRequest)25 ServletContext (javax.servlet.ServletContext)25 Test (org.testng.annotations.Test)25 HttpSession (javax.servlet.http.HttpSession)24 MockFilterChain (org.springframework.mock.web.MockFilterChain)24 InvocationOnMock (org.mockito.invocation.InvocationOnMock)22 Properties (java.util.Properties)19