2016-12-13 95 views
0

我需要在自定义过滤器中使用Spring Security的AuthenticationManagerBean,但它似乎总是给一个null。我正在使用1.3.8的弹簧引导。下面是从代码片段:自动装配春天AuthenticationManager过滤器总是给出空

@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会为空。

帮助表示赞赏。

+0

您是否阅读过http://stackoverflow.com/questions/5417509/get-instance-of-authenticationmanager-manually或那一个http://stackoverflow.com/questions/21633555/how-to-inject-authenticationmanager -using-java-configuration-in-a-custom-filter? – Victor

+0

你读过[link](http://stackoverflow.com/questions/21633555/how-to-inject-authenticationmanager-using-java-configuration-in-a-custom-filter)还是那个[Get instance of手动AuthenticationManager(http://stackoverflow.com/questions/5417509/get-instance-of-authenticationmanager-manually)? – Victor

+0

你读过[link](http://stackoverflow.com/questions/21633555/how-to-inject-authenticationmanager-using-java-configuration-in-a-custom-filter)还是那个[Get instance of手动AuthenticationManager(http://stackoverflow.com/questions/5417509/get-instance-of-authenticationmanager-manually)? – Victor

回答

0

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

另外,我认为你需要@Component在你的Filter上。

祝你好运。

+0

感谢您的建议。它仍然给予null。我也尝试过使用'@ Qualifier'和'@ Autowired',但是同样的事情。 –

+0

我认为你的过滤器需要@Component。我收回我对重命名该方法的建议;我错过了它覆盖了现有的方法。 –

+0

它没有太大的改变,谢谢无论如何,我发现了另一种设置身份验证的方式。 –