2015-08-24 74 views
1

一起使用我正在開發Spring Boot + spring security的應用程序。對於相同的我已經定義了一個過濾器。身份驗證篩選器不能與SpringBoot

@Override 
protected void configure(HttpSecurity http) throws Exception { 
    http.csrf().disable() 
     .authorizeRequests() 
     .antMatchers("/authtoken").permitAll() 
     .antMatchers("/authenticate**").permitAll() 
     .antMatchers("/authfailure").permitAll() 
     .antMatchers("/**").authenticated() 
     .and() 
      .addFilterBefore(tokenFilter, UsernamePasswordAuthenticationFilter.class) 
      .addFilterAfter(accessFilter, UsernamePasswordAuthenticationFilter.class) 
      .authenticationProvider(tokenAuthenticationProvider) 
      .antMatcher("/**").exceptionHandling().authenticationEntryPoint(authenticationEntryPoint); 

} 

哪裏tokenFilter是AuthTokenFilter(類具有代碼進行驗證和被注入到使用@Inject)的一個實例。

AuthTokenFilter實現了Filter接口的方法。

public class AuthTokenFilter implements Filter { 
ServletContext sc ; 
@Override 
    public void init(FilterConfig fc) throws ServletException { 
    sc = fc.getServletContext(); 
    } 

    @Override 
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain fc) throws IOException, ServletException { 
------- 
------- 
} 

我的問題是當我運行應用程序使用SpringBoot,它運行良好。但是當我創建一個war並在tomcat中運行它時,init和doFilter都不會被請求調用。因此它返回未授權。

對於accessFilter也是如此。

有沒有人知道背後的原因?或者我需要做些什麼改變才能讓我的應用程序在tomcat上工作?

+0

我會說,因爲你的整個安全設置是錯誤的。我懷疑由於它是'Filter',並且在嵌入模式下運行時將其註冊爲'@ Bean',所以過濾器被servlet容器調用,而不是Spring Security調用。我懷疑後者是否還在工作。 –

+0

是的@M.Deinum,我明白這可能不是最好的做法。你能建議我,讓這個更好嗎? – biraj

+0

對於初學者,刪除'@ Named'註釋,以便它不被拾取並添加到普通的過濾器鏈中。如果你有'@ Bean'方法來創建過濾器,那麼也刪除它。只需創建一個實例並使用彈簧安全過濾器鏈註冊它。我懷疑它然後開始在兩種情況下失敗... –

回答

0

您使用的是什麼Tomcat版本?

我不知道,但嘗試這個辦法:

在課堂AuthTokenFilter的聲明,添加anotation @Component

我有一個項目,過濾器和只寫:

@Component 
@Order(Ordered.HIGHEST_PRECEDENCE) 
public class SimpleCORSFilter implements Filter ... 

+0

謝謝@喬治,這可能不起作用我已經使用@命名註釋。我正在使用Java 8的tomcat 8. – biraj

+0

@biraj使用SpringBootServletInitializer? –

+0

:是的,我正在使用它,否則不會創建一個可部署的戰爭。 – biraj