@Override
  public void doFilter(HttpRequest request, HttpResponse response, FilterChain chain) throws IOException {
    String relayState = request.getParameter(RELAY_STATE_PARAMETER);

    if (isSamlValidation(relayState)) {

      URI redirectionEndpointUrl = URI.create(server.getContextPath() + "/")
        .resolve(SAML_VALIDATION_CONTROLLER_CONTEXT + "/")
        .resolve(SAML_VALIDATION_KEY);
      String samlResponse = StringEscapeUtils.escapeHtml3(request.getParameter(SAML_RESPONSE_PARAMETER));
      String csrfToken = getCsrfTokenFromRelayState(relayState);

      String nonce = SamlValidationCspHeaders.addCspHeadersWithNonceToResponse(response);

      String template = StringUtils.replaceEachRepeatedly(redirectionPageTemplate,
        new String[]{"%NONCE%", "%WEB_CONTEXT%", "%VALIDATION_URL%", "%SAML_RESPONSE%", "%CSRF_TOKEN%"},
        new String[]{nonce, server.getContextPath(), redirectionEndpointUrl.toString(), samlResponse, csrfToken});

      response.setContentType("text/html");
      response.getWriter().print(template);
      return;
    }
    chain.doFilter(request, response);
  }
@Test
  public void do_filter_validation_wrong_SAML_response() throws IOException {
    HttpRequest servletRequest = mock(HttpRequest.class);
    HttpResponse servletResponse = mock(HttpResponse.class);
    FilterChain filterChain = mock(FilterChain.class);

    String maliciousSaml = "test\"</input><script>/*hack website*/</script><input value=\"";

    when(servletRequest.getParameter(matches("SAMLResponse"))).thenReturn(maliciousSaml);
    when(servletRequest.getParameter(matches("RelayState"))).thenReturn("validation-query/CSRF_TOKEN");
    PrintWriter pw = mock(PrintWriter.class);
    when(servletResponse.getWriter()).thenReturn(pw);

    underTest.doFilter(servletRequest, servletResponse, filterChain);

    ArgumentCaptor<String> htmlProduced = ArgumentCaptor.forClass(String.class);
    verify(pw).print(htmlProduced.capture());
    CSP_HEADERS.forEach(h -> verify(servletResponse).setHeader(eq(h), anyString()));
    assertThat(htmlProduced.getValue()).doesNotContain("<script>/*hack website*/</script>");
    assertThat(htmlProduced.getValue()).contains("action=\"contextPath/saml/validation\"");
  }