@Override
  public void doFilter(HttpRequest request, HttpResponse response, FilterChain chain) throws IOException {
    try {
      userSession.checkIsSystemAdministrator();
    } catch (ForbiddenException e) {
      AuthenticationError.handleError(request, response, "User needs to be logged in as system administrator to access this page.");
      return;
    }

    String csrfState = oAuthCsrfVerifier.generateState(request, response);

    try {
      samlAuthenticator.initLogin(oAuth2ContextFactory.generateCallbackUrl(SamlIdentityProvider.KEY),
        VALIDATION_RELAY_STATE + "/" + csrfState, request, response);
    } catch (IllegalArgumentException | IllegalStateException e) {
      response.sendRedirect("/" + SAML_VALIDATION_CONTROLLER_CONTEXT + "/" + SAML_VALIDATION_KEY + "?CSRFToken=" + csrfState);
    }
  }
@Test
  public void do_filter_as_admin_with_init_issues() throws IOException {
    userSession.logIn().setSystemAdministrator();
    HttpRequest servletRequest = mock(HttpRequest.class);
    HttpResponse servletResponse = mock(HttpResponse.class);
    FilterChain filterChain = mock(FilterChain.class);
    String callbackUrl = "http://localhost:9000/api/validation_test";
    when(oAuth2ContextFactory.generateCallbackUrl(anyString()))
      .thenReturn(callbackUrl);

    mockCsrfTokenGeneration(servletRequest, servletResponse);
    doThrow(new IllegalStateException()).when(samlAuthenticator).initLogin(any(), any(), any(), any());

    underTest.doFilter(servletRequest, servletResponse, filterChain);

    verify(servletResponse).sendRedirect("/saml/validation?CSRFToken=CSRF_TOKEN");
  }