2016-12-13 68 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

它沒有太大的改變,謝謝無論如何,我發現了另一種設置身份驗證的方式。 –