1

I need to use Spring Security's AuthenticationManagerBean inside a custom filter, but it seem to always give a null. I am using spring boot 1.3.8. Here is a snippet from the code:

@Configuration
public class WebSecurityConfig extends WebSecurityConfigurerAdapter  {
    

        @Override
        @Bean(name = BeanIds.AUTHENTICATION_MANAGER)
        public AuthenticationManager authenticationManagerBean() throws Exception {
            return super.authenticationManagerBean();
        }
     
     @Override
     protected void configure(AuthenticationManagerBuilder auth) throws Exception {
       
     }
     
    

}

The filter code:

public class MyFilter extends OncePerRequestFilter {
    
  private TokenExtractor tokenExtractor = new BearerTokenExtractor();

  @Autowired
    private AuthenticationManager authenticationManager;
    

    
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
            throws ServletException, IOException {
        
       
            //some checks

Authentication receivedAuthentication = tokenExtractor.extract(request);
receivedAuthentication.setAuthenticated(true);
                authenticationManager.authenticate(receivedAuthentication);
                 SecurityContextHolder.getContext().setAuthentication(receivedAuthentication);
            
        }
    }
    
    

}

An exception is thrown because authenticationManager is null.

cigien
  • 57,834
  • 11
  • 73
  • 112
zakaria amine
  • 3,412
  • 2
  • 20
  • 35
  • Have you read that http://stackoverflow.com/questions/5417509/get-instance-of-authenticationmanager-manually or that one http://stackoverflow.com/questions/21633555/how-to-inject-authenticationmanager-using-java-configuration-in-a-custom-filter ? – Victor Dec 14 '16 at 13:04
  • Have you read that [link](http://stackoverflow.com/questions/21633555/how-to-inject-authenticationmanager-using-java-configuration-in-a-custom-filter) or that one [Get instance of AuthenticationManager Manually](http://stackoverflow.com/questions/5417509/get-instance-of-authenticationmanager-manually) ? – Victor Dec 14 '16 at 13:15
  • Have you read that [link](http://stackoverflow.com/questions/21633555/how-to-inject-authenticationmanager-using-java-configuration-in-a-custom-filter) or that one [Get instance of AuthenticationManager Manually](http://stackoverflow.com/questions/5417509/get-instance-of-authenticationmanager-manually) ? – Victor Dec 14 '16 at 13:17
  • 1
    Yeah, I have tried that as well, still null – zakaria amine Dec 14 '16 at 14:28

1 Answers1

0

The value of BeanIds.AUTHENTICATION_MANAGER is "org.springframework.security.authenticationManager"; therefore, you do not have a bean named "authenticationManager".

Also, I think you need @Component on your Filter.

cigien
  • 57,834
  • 11
  • 73
  • 112
Jamie Bisotti
  • 2,605
  • 19
  • 23