title: Infinite loop in Spring boot AuthenticationFilter
body: <p>We have recently converted Java configured spring application to spring boot and the old application was working fine but however after converting it into spring boot project we are having serious problems in endpoints that were secured by JWT tokens all of them are creating an endless loop and finally throwing  <code>StackOverflow</code> Exceptions.</p>
  
  <p>Below is the very abstract example of the whole JWT token filer without actual code because the original code is very lengthy and I feel this is enough for someone who is good at spring to understand.</p>
  
  <pre><code>public class TokenAuthenticationFilter extends UsernamePasswordAuthenticationFilter {
  
  
  
    public TokenAuthenticationFilter() {
      setAuthenticationManager(new AuthenticationManager() {
          @Override
          public Authentication authenticate(Authentication authentication) throws AuthenticationException {
              return null; // no different in the original code 
          }
      });
      setAuthenticationSuccessHandler(new SimpleUrlAuthenticationSuccessHandler() {
          @Override
          protected String determineTargetUrl(HttpServletRequest request, HttpServletResponse response) {
              String context = request.getContextPath();
              String fullURL = request.getRequestURI();
              String url = fullURL.substring(fullURL.indexOf(context) + context.length());
              return url;
          }
  
          @Override
          public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication auth) throws IOException, ServletException {
              String url = determineTargetUrl(request, response);
              request.getRequestDispatcher(url).forward(request, response);
          }
      });
      setRequiresAuthenticationRequestMatcher(new RequestMatcher() {
          public boolean matches(HttpServletRequest request) {
              return getTokenRequest(request);
          }
      });
  }
  
  
  private boolean getTokenRequest(HttpServletRequest request) {
      String userAuthToken = request.getHeader("X-Auth-Token");
      return userAuthToken != null;
  }
  
  
  @Override
  public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {
  
      List&lt;GrantedAuthority&gt; roles = new ArrayList&lt;GrantedAuthority&gt;(1);
      roles.add(new SimpleGrantedAuthority("USER_ROLE"));
      UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken("imaa95@gmail.com", "", roles);
      return authRequest;
   }
  }
  </code></pre>
  
  <p>Basically in the actual code token is validated within the <code>attemptAuthentication</code> method once that is done spring calls the <code>onAuthenticationSuccess</code> method, inside of that based on a logic we are forwarding the requests to the controller </p>
  
  <p><code>request.getRequestDispatcher(url).forward(request, response);
  </code></p>
  
  <p>I think this is the reason for the infinite loop because this creates a new request that will again be captured by the same filter, but the strange thing is that this exact code worked without any issue in the previous java based configuration so we would really happy if someone can spot the issue and provide us a way to fix it with minimum code changes</p>
  
  <p>As requested here is the security config</p>
  
  <pre><code>@Override
  protected void configure(HttpSecurity http) throws Exception {
          http.csrf().disable();
          http.authenticationProvider(daoAuthenticationProvider())
              .authorizeRequests()
              .antMatchers("/", "/allData").permitAll()
              .anyRequest().authenticated()
              .and()
                  .sessionManagement()
                  .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
              .and()
                  .formLogin().usernameParameter("email").passwordParameter("password")
                  .successHandler(getLoginSuccessHandler())
                  .failureHandler(new AuthenticationFailureHandler() {
                      @Override
                      public void onAuthenticationFailure(HttpServletRequest request,
                                                          HttpServletResponse response,
                                                          AuthenticationException e) throws IOException,
                              ServletException {
                          response.getWriter().write("Login Failed :(");
                      }
                  })
              .and()
                  .logout()
                      .logoutRequestMatcher( new AntPathRequestMatcher( "/logout" ) )
                      .logoutSuccessHandler( getLogoutSuccessHandler() )
                      .deleteCookies( "uc" )
                      .invalidateHttpSession( true )
                      .and()
              .exceptionHandling()
              .authenticationEntryPoint(getEntryPoint());
  
      http.addFilterBefore(new TokenAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class);
  }
  </code></pre>