自动装配Spring AuthenticationManager过滤器始终为null

时间:2016-12-13 21:26:30

标签: java spring spring-boot spring-security

我需要在自定义过滤器中使用Spring Security的AuthenticationManagerBean,但它似乎总是给出null。我正在使用弹簧靴1.3.8。以下是代码中的代码段:

@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 {

     }



}

过滤器代码:

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);

        }
    }



}

抛出异常,因为authenticationManager为null。

帮助表示赞赏。

1 个答案:

答案 0 :(得分:0)

BeanIds.AUTHENTICATION_MANAGER的值是" org.springframework.security.authenticationManager" ;因此,您没有名为" authenticationManager" 的bean。

另外,我认为你的过滤器需要@Component。

祝你好运。