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.