@Test public void testJWTFilter() throws Exception { UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken( "test-user", "test-password", Collections.singletonList(new SimpleGrantedAuthority(AuthoritiesConstants.USER)) ); String jwt = tokenProvider.createToken(authentication, false); MockHttpServletRequest request = new MockHttpServletRequest(); request.addHeader(JWTConfigurer.AUTHORIZATION_HEADER, "Bearer " + jwt); request.setRequestURI("/api/test"); MockHttpServletResponse response = new MockHttpServletResponse(); MockFilterChain filterChain = new MockFilterChain(); jwtFilter.doFilter(request, response, filterChain); assertThat(response.getStatus()).isEqualTo(HttpStatus.OK.value()); assertThat(SecurityContextHolder.getContext().getAuthentication().getName()).isEqualTo("test-user"); assertThat(SecurityContextHolder.getContext().getAuthentication().getCredentials().toString()).isEqualTo(jwt); }
@Test public void onNonRepositoryRequestShouldPassTrough() throws Exception { MockFilterChain filterChain = new MockFilterChain(); MockHttpServletRequest request = new MockHttpServletRequest(servletContext); request.setMethod("GET"); request.setContextPath(""); request.setServletPath(null); request.setPathInfo(null); request.setRequestURI("/api/somethingDifferent/"); request.addHeader("Accept", "*/*"); MockHttpServletResponse response = new MockHttpServletResponse(); filter.doFilter(request, response, filterChain); // no content set yet Assert.assertEquals(0, response.getContentLength()); }
@Test public void test_filter_wrapper() throws IOException, ServletException { HttpServlet servlet = new HttpServlet() { @Override public void service(ServletRequest req, ServletResponse res) throws ServletException, IOException { assertThat(req).isInstanceOf(SimpleSessionRequest.class); super.service(req, res); } }; mockFilterChain = new MockFilterChain(servlet, filter); filter.doFilter(mockRequest, mockResponse, mockFilterChain); assertThat(mockRequest.getAttribute(SimpleSessionFilter.class.getName().concat(".VISITED"))) .isEqualTo(Boolean.TRUE); }
public String[] call() throws Exception { synchronized (concurrentThreads) { concurrentThreads.increment(); //System.out.println("concurrentThreads = " + concurrentThreads); } try { MockHttpServletRequest request = new MockHttpServletRequest(); String randomValue = UUID.randomUUID().toString(); String param_name = "param_name"; request.setParameter(param_name, randomValue); MockHttpServletResponse response = new MockHttpServletResponse(); MockFilterChain filterChain = new MockFilterChain(); try { filter.doFilter(request, response, filterChain); } catch (Exception e) { throw new IllegalStateException(e.getMessage(), e); } String filteredValue = filterChain.getRequest().getParameter(param_name); //return the original parameter and filtered parameter return new String[]{filteredValue, randomValue}; } finally { synchronized (concurrentThreads) { concurrentThreads.decrement(); } } }
@Test public void testRedirectIssuedIfXForwardedProtoHeaderIsHttp() throws Exception { MockHttpServletRequest request = new MockHttpServletRequest("any", "/path/morepath.extension?a=b&c=d"); request.setScheme("http"); request.setServerName("somehost.com"); request.setServerPort(81); request.addHeader("X-Forwarded-Proto", "http"); MockHttpServletResponse response = new MockHttpServletResponse(); MockFilterChain filterChain = new MockFilterChain(); new HttpsOnlyFilter().doFilter(request, response, filterChain); assertThat(response.getRedirectedUrl(), equalTo("https://somehost.com/path/morepath.extension?a=b&c=d")); assertThat(filterChain.getRequest(), nullValue()); assertThat(filterChain.getResponse(), nullValue()); }
@Test public void testUnacceptableRequestContentType() throws Exception { MockFilterChain filterChain = new MockFilterChain(); MockHttpServletRequest request = new MockHttpServletRequest(servletContext); request.setMethod("GET"); request.setContextPath(""); request.setServletPath(null); request.setPathInfo(null); request.setRequestURI("/api/tasks/"); request.setContentType(JsonApiMediaType.APPLICATION_JSON_API); request.addHeader("Accept", "application/xml"); MockHttpServletResponse response = new MockHttpServletResponse(); katharsisFilter.doFilter(request, response, filterChain); assertEquals(HttpServletResponse.SC_UNSUPPORTED_MEDIA_TYPE, response.getStatus()); String responseContent = response.getContentAsString(); assertTrue(responseContent == null || "".equals(responseContent.trim())); }
@Test public void notAnErrorButNotOK() throws Exception { this.chain = new MockFilterChain() { @Override public void doFilter(ServletRequest request, ServletResponse response) throws IOException, ServletException { ((HttpServletResponse) response).setStatus(201); super.doFilter(request, response); response.flushBuffer(); } }; this.filter.doFilter(this.request, this.response, this.chain); assertThat(((HttpServletResponse) this.chain.getResponse()).getStatus()) .isEqualTo(201); assertThat(((HttpServletResponse) ((HttpServletResponseWrapper) this.chain .getResponse()).getResponse()).getStatus()).isEqualTo(201); assertThat(this.response.isCommitted()).isTrue(); }
@Test public void unauthorizedWithErrorPath() throws Exception { this.filter.addErrorPages(new ErrorPage("/error")); this.chain = new MockFilterChain() { @Override public void doFilter(ServletRequest request, ServletResponse response) throws IOException, ServletException { ((HttpServletResponse) response).sendError(401, "UNAUTHORIZED"); super.doFilter(request, response); } }; this.filter.doFilter(this.request, this.response, this.chain); assertThat(this.chain.getRequest()).isEqualTo(this.request); HttpServletResponseWrapper wrapper = (HttpServletResponseWrapper) this.chain .getResponse(); assertThat(wrapper.getResponse()).isEqualTo(this.response); assertThat(this.response.isCommitted()).isTrue(); assertThat(wrapper.getStatus()).isEqualTo(401); // The real response has to be 401 as well... assertThat(this.response.getStatus()).isEqualTo(401); assertThat(this.response.getForwardedUrl()).isEqualTo("/error"); }
@Test public void responseUncommittedWithoutErrorPage() throws Exception { this.chain = new MockFilterChain() { @Override public void doFilter(ServletRequest request, ServletResponse response) throws IOException, ServletException { ((HttpServletResponse) response).sendError(400, "BAD"); super.doFilter(request, response); } }; this.filter.doFilter(this.request, this.response, this.chain); assertThat(this.chain.getRequest()).isEqualTo(this.request); assertThat(((HttpServletResponseWrapper) this.chain.getResponse()).getResponse()) .isEqualTo(this.response); assertThat(((HttpServletResponseWrapper) this.chain.getResponse()).getStatus()) .isEqualTo(400); assertThat(this.response.getForwardedUrl()).isNull(); assertThat(this.response.isCommitted()).isTrue(); }
@Test public void globalError() throws Exception { this.filter.addErrorPages(new ErrorPage("/error")); this.chain = new MockFilterChain() { @Override public void doFilter(ServletRequest request, ServletResponse response) throws IOException, ServletException { ((HttpServletResponse) response).sendError(400, "BAD"); super.doFilter(request, response); } }; this.filter.doFilter(this.request, this.response, this.chain); assertThat(((HttpServletResponseWrapper) this.chain.getResponse()).getStatus()) .isEqualTo(400); assertThat(this.request.getAttribute(RequestDispatcher.ERROR_STATUS_CODE)) .isEqualTo(400); assertThat(this.request.getAttribute(RequestDispatcher.ERROR_MESSAGE)) .isEqualTo("BAD"); assertThat(this.request.getAttribute(RequestDispatcher.ERROR_REQUEST_URI)) .isEqualTo("/test/path"); assertThat(this.response.isCommitted()).isTrue(); assertThat(this.response.getForwardedUrl()).isEqualTo("/error"); }
@Test public void statusError() throws Exception { this.filter.addErrorPages(new ErrorPage(HttpStatus.BAD_REQUEST, "/400")); this.chain = new MockFilterChain() { @Override public void doFilter(ServletRequest request, ServletResponse response) throws IOException, ServletException { ((HttpServletResponse) response).sendError(400, "BAD"); super.doFilter(request, response); } }; this.filter.doFilter(this.request, this.response, this.chain); assertThat(((HttpServletResponseWrapper) this.chain.getResponse()).getStatus()) .isEqualTo(400); assertThat(this.request.getAttribute(RequestDispatcher.ERROR_STATUS_CODE)) .isEqualTo(400); assertThat(this.request.getAttribute(RequestDispatcher.ERROR_MESSAGE)) .isEqualTo("BAD"); assertThat(this.request.getAttribute(RequestDispatcher.ERROR_REQUEST_URI)) .isEqualTo("/test/path"); assertThat(this.response.isCommitted()).isTrue(); assertThat(this.response.getForwardedUrl()).isEqualTo("/400"); }
@Test public void statusErrorWithCommittedResponse() throws Exception { this.filter.addErrorPages(new ErrorPage(HttpStatus.BAD_REQUEST, "/400")); this.chain = new MockFilterChain() { @Override public void doFilter(ServletRequest request, ServletResponse response) throws IOException, ServletException { ((HttpServletResponse) response).sendError(400, "BAD"); response.flushBuffer(); super.doFilter(request, response); } }; this.filter.doFilter(this.request, this.response, this.chain); assertThat(((HttpServletResponseWrapper) this.chain.getResponse()).getStatus()) .isEqualTo(400); assertThat(this.response.isCommitted()).isTrue(); assertThat(this.response.getForwardedUrl()).isNull(); }
@Test public void exceptionError() throws Exception { this.filter.addErrorPages(new ErrorPage(RuntimeException.class, "/500")); this.chain = new MockFilterChain() { @Override public void doFilter(ServletRequest request, ServletResponse response) throws IOException, ServletException { super.doFilter(request, response); throw new RuntimeException("BAD"); } }; this.filter.doFilter(this.request, this.response, this.chain); assertThat(((HttpServletResponseWrapper) this.chain.getResponse()).getStatus()) .isEqualTo(500); assertThat(this.request.getAttribute(RequestDispatcher.ERROR_STATUS_CODE)) .isEqualTo(500); assertThat(this.request.getAttribute(RequestDispatcher.ERROR_MESSAGE)) .isEqualTo("BAD"); assertThat(this.request.getAttribute(RequestDispatcher.ERROR_EXCEPTION_TYPE)) .isEqualTo(RuntimeException.class.getName()); assertThat(this.request.getAttribute(RequestDispatcher.ERROR_REQUEST_URI)) .isEqualTo("/test/path"); assertThat(this.response.isCommitted()).isTrue(); assertThat(this.response.getForwardedUrl()).isEqualTo("/500"); }
@Test public void subClassExceptionError() throws Exception { this.filter.addErrorPages(new ErrorPage(RuntimeException.class, "/500")); this.chain = new MockFilterChain() { @Override public void doFilter(ServletRequest request, ServletResponse response) throws IOException, ServletException { super.doFilter(request, response); throw new IllegalStateException("BAD"); } }; this.filter.doFilter(this.request, this.response, this.chain); assertThat(((HttpServletResponseWrapper) this.chain.getResponse()).getStatus()) .isEqualTo(500); assertThat(this.request.getAttribute(RequestDispatcher.ERROR_STATUS_CODE)) .isEqualTo(500); assertThat(this.request.getAttribute(RequestDispatcher.ERROR_MESSAGE)) .isEqualTo("BAD"); assertThat(this.request.getAttribute(RequestDispatcher.ERROR_EXCEPTION_TYPE)) .isEqualTo(IllegalStateException.class.getName()); assertThat(this.request.getAttribute(RequestDispatcher.ERROR_REQUEST_URI)) .isEqualTo("/test/path"); assertThat(this.response.isCommitted()).isTrue(); }
@Test public void responseIsCommittedWhenExceptionIsThrownDuringAsyncDispatch() throws Exception { this.filter.addErrorPages(new ErrorPage("/error")); setUpAsyncDispatch(); this.chain = new MockFilterChain() { @Override public void doFilter(ServletRequest request, ServletResponse response) throws IOException, ServletException { super.doFilter(request, response); throw new RuntimeException("BAD"); } }; this.filter.doFilter(this.request, this.response, this.chain); assertThat(this.chain.getRequest()).isEqualTo(this.request); assertThat(((HttpServletResponseWrapper) this.chain.getResponse()).getResponse()) .isEqualTo(this.response); assertThat(this.response.isCommitted()).isTrue(); }
@Test public void responseIsCommittedWhenStatusIs400PlusDuringAsyncDispatch() throws Exception { this.filter.addErrorPages(new ErrorPage("/error")); setUpAsyncDispatch(); this.chain = new MockFilterChain() { @Override public void doFilter(ServletRequest request, ServletResponse response) throws IOException, ServletException { super.doFilter(request, response); ((HttpServletResponse) response).sendError(400, "BAD"); } }; this.filter.doFilter(this.request, this.response, this.chain); assertThat(this.chain.getRequest()).isEqualTo(this.request); assertThat(((HttpServletResponseWrapper) this.chain.getResponse()).getResponse()) .isEqualTo(this.response); assertThat(this.response.isCommitted()).isTrue(); }
@Test public void nestedServletExceptionIsUnwrapped() throws Exception { this.filter.addErrorPages(new ErrorPage(RuntimeException.class, "/500")); this.chain = new MockFilterChain() { @Override public void doFilter(ServletRequest request, ServletResponse response) throws IOException, ServletException { super.doFilter(request, response); throw new NestedServletException("Wrapper", new RuntimeException("BAD")); } }; this.filter.doFilter(this.request, this.response, this.chain); assertThat(((HttpServletResponseWrapper) this.chain.getResponse()).getStatus()) .isEqualTo(500); assertThat(this.request.getAttribute(RequestDispatcher.ERROR_STATUS_CODE)) .isEqualTo(500); assertThat(this.request.getAttribute(RequestDispatcher.ERROR_MESSAGE)) .isEqualTo("BAD"); assertThat(this.request.getAttribute(RequestDispatcher.ERROR_EXCEPTION_TYPE)) .isEqualTo(RuntimeException.class.getName()); assertThat(this.request.getAttribute(RequestDispatcher.ERROR_REQUEST_URI)) .isEqualTo("/test/path"); assertThat(this.response.isCommitted()).isTrue(); assertThat(this.response.getForwardedUrl()).isEqualTo("/500"); }
@Test public void delegatingFilterProxyRegistrationBeansSkipsTargetBeanNames() throws Exception { addEmbeddedServletContainerFactoryBean(); DelegatingFilterProxyRegistrationBean initializer = new DelegatingFilterProxyRegistrationBean( "filterBean"); this.context.registerBeanDefinition("initializerBean", beanDefinition(initializer)); BeanDefinition filterBeanDefinition = beanDefinition( new IllegalStateException("Create FilterBean Failure")); filterBeanDefinition.setLazyInit(true); this.context.registerBeanDefinition("filterBean", filterBeanDefinition); this.context.refresh(); ServletContext servletContext = getEmbeddedServletContainerFactory() .getServletContext(); verify(servletContext, atMost(1)).addFilter(anyString(), this.filterCaptor.capture()); // Up to this point the filterBean should not have been created, calling // the delegate proxy will trigger creation and an exception this.thrown.expect(BeanCreationException.class); this.thrown.expectMessage("Create FilterBean Failure"); this.filterCaptor.getValue().init(new MockFilterConfig()); this.filterCaptor.getValue().doFilter(new MockHttpServletRequest(), new MockHttpServletResponse(), new MockFilterChain()); }
@Before public void init() { initMocks(this); this.tracer = new DefaultTracer(new DelegateSampler(), new Random(), new DefaultSpanNamer(), this.spanLogger, this.spanReporter) { @Override public Span continueSpan(Span span) { TraceFilterTests.this.span = super.continueSpan(span); return TraceFilterTests.this.span; } }; this.request = builder().buildRequest(new MockServletContext()); this.response = new MockHttpServletResponse(); this.response.setContentType(MediaType.APPLICATION_JSON_VALUE); this.filterChain = new MockFilterChain(); this.httpTraceKeysInjector = new HttpTraceKeysInjector(this.tracer, this.traceKeys); }
@Test public void shouldCreateAuthenticationInSecurityContextFromQueryString() throws Exception { MockHttpServletRequest request = new MockHttpServletRequest(); request.setQueryString("id=123&otherid=abc"); MockHttpServletResponse response = new MockHttpServletResponse(); MockFilterChain filterChain = new MockFilterChain(); new WalletAuthenticationFilter().doFilterInternal(request, response, filterChain); Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); assertThat(authentication.getPrincipal(), equalTo("123")); assertThat(authentication.getCredentials(), equalTo("abc")); assertThat(authentication.isAuthenticated(), equalTo(false)); assertThat(filterChain.getRequest(), sameInstance(request)); assertThat(filterChain.getResponse(), sameInstance(response)); }
@Test public void shouldCreateAuthenticationInSecurityContextForApplePassAuthorizationHeader() throws Exception { MockHttpServletRequest request = new MockHttpServletRequest(); String authorizationToken = "123:abc"; String encodedAuthorizationToken = Base64.getMimeEncoder(Integer.MAX_VALUE, new byte[]{'\r', '\n'}).encodeToString(authorizationToken.getBytes(StandardCharsets.ISO_8859_1)); request.addHeader("authorization", "ApplePass " + encodedAuthorizationToken); MockHttpServletResponse response = new MockHttpServletResponse(); MockFilterChain filterChain = new MockFilterChain(); new WalletAuthenticationFilter().doFilterInternal(request, response, filterChain); Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); assertThat(authentication.getPrincipal(), equalTo("123")); assertThat(authentication.getCredentials(), equalTo("abc")); assertThat(authentication.isAuthenticated(), equalTo(false)); assertThat(filterChain.getRequest(), sameInstance(request)); assertThat(filterChain.getResponse(), sameInstance(response)); }