title: How to configure a custom filter programatically in Spring Security?
body: <p>On user authentication i need to retrieve his remote address and remote host.<br>
  I'm trying to implement a custom filter to support this, but i'm getting "<strong>authenticationManager must be specified</strong>".<br>
  Another doubt is... What is the correct way to register a custom filter using programmatically ?</p>
  
  <p>Configuration using annotations:  </p>
  
  <pre><code>@Configuration
  @EnableWebSecurity
  public class SecurityApplicationConfiguration extends WebSecurityConfigurerAdapter {
  
    @Autowired
    private SCAAuthenticationFilter scaAuthenticationFilter;
  
    @Autowired
    private SCAAuthenticationProvider scaAuthenticationProvider;
  
    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
      auth.authenticationProvider(scaAuthenticationProvider);
    }
  
    @Override
    public void configure(WebSecurity web) throws Exception {
      web.ignoring().antMatchers("/resources/**");
    }
  
    @Override
    protected void configure(HttpSecurity http) throws Exception {
      http
        .addFilter(scaAuthenticationFilter) // What is the right way ?
        .addFilterBefore(scaAuthenticationFilter, AbstractAuthenticationProcessingFilter.class) // What is the right way ?
        .csrf().disable()
        .authorizeRequests()
          .antMatchers("/manual/**").authenticated()
          .and()
        .formLogin()
          .loginPage("/login")
          .loginProcessingUrl("/login")
          .failureUrl("/login?error=true")
          .defaultSuccessUrl("/manual")
          .permitAll()
          .and()
        .logout()
          .logoutUrl("/logout")
          .logoutSuccessUrl("/login")
          .permitAll()
          .and();
    }
  }
  </code></pre>
  
  <p>The custom filter:  </p>
  
  <pre><code>@Component
  public class SCAAuthenticationFilter extends UsernamePasswordAuthenticationFilter {
  
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {
      if (!request.getMethod().equals("POST")) {
        throw new AuthenticationServiceException("Authentication method not supported: " + request.getMethod());
      }
      String username = obtainUsername(request);
      String password = obtainPassword(request);
      String remoteHost = request.getRemoteHost();
      String remoteAddr = request.getRemoteAddr();
      if (username == null) {
        username = "";
      }
      if (password == null) {
        password = "";
      }
      username = username.trim();
      SCAAuthenticationToken scaAuthenticationToken = new SCAAuthenticationToken(username, password, remoteHost, remoteAddr);
      setDetails(request, scaAuthenticationToken);
      return getAuthenticationManager().authenticate(scaAuthenticationToken);
    }
  
  }
  </code></pre>