title: spring security: BadCredendtials exception not handled by the chain and not returning 401
body: <p>Good morning,</p>
  
  <p>I was following <a href="https://octoperf.com/blog/2018/03/08/securing-rest-api-spring-security/" rel="nofollow noreferrer">this tutorial</a>, in order to make spring security works with jwt token.</p>
  
  <p><strong>* my environment versions*</strong>
  spring boot : 2.0.1 RELEASE</p>
  
  <p><strong><em>Spring security config</em></strong></p>
  
  <pre><code>@Override
  protected void configure(final HttpSecurity http) throws Exception {
      http
              .cors().configurationSource(request -&gt; getCorsConfiguration())
              .and()
              .sessionManagement()
              .sessionCreationPolicy(STATELESS)
              .and()
              .exceptionHandling()
              .defaultAuthenticationEntryPointFor(forbiddenEntryPoint(), PROTECTED_URLS)
              .and()
              .authenticationProvider(provider)
              .addFilterBefore(restAuthenticationFilter(), AnonymousAuthenticationFilter.class)
              .authorizeRequests()
              .requestMatchers(PROTECTED_URLS)
              .authenticated()
              .and()
              .csrf().disable()
              .formLogin().disable()
              .httpBasic().disable()
              .logout().disable();
  }
  @Bean
  TokenAuthenticationFilter restAuthenticationFilter() throws Exception {
      final TokenAuthenticationFilter filter = new TokenAuthenticationFilter(PROTECTED_URLS);
      filter.setAuthenticationManager(authenticationManager());
      filter.setAuthenticationSuccessHandler(successHandler());
      return filter;
  }
  
  @Bean
  SimpleUrlAuthenticationSuccessHandler successHandler() {
      final SimpleUrlAuthenticationSuccessHandler successHandler = new SimpleUrlAuthenticationSuccessHandler();
      successHandler.setRedirectStrategy((HttpServletRequest request, HttpServletResponse response, String url) -&gt; {
          // no redirection strategy
      });
      return successHandler;
  }
  
  /**
   * Disable Spring boot automatic filter registration.
   */
  @Bean
  FilterRegistrationBean disableAutoRegistration(final TokenAuthenticationFilter filter) {
      final FilterRegistrationBean registration = new FilterRegistrationBean(filter);
      registration.setEnabled(false);
      return registration;
  }
  
  @Bean
  AuthenticationEntryPoint forbiddenEntryPoint() {
      return new HttpStatusEntryPoint(FORBIDDEN);
  }
  </code></pre>
  
  <p><strong><em>Context:</em></strong></p>
  
  <p>Token authentication filter is throwing BadCredentialsException, in case the token does not match expectation.</p>
  
  <p><strong><em>Expected behaviour:</em></strong></p>
  
  <p>spring  chain will catch this error and return 401 error back to the user.</p>
  
  <p><strong><em>Current Behaviour:</em></strong></p>
  
  <p>the server crashes with 500 error. the error is not handled by spring security.</p>