2016-12-22 24 views
0

我在擴展一個WebSecurityConfigurerAdapter來覆蓋configure方法。 我的目標是在繞過登錄頁面並進行手動驗證的特定URL上放置過濾器。爲此,我需要只在用戶第一次嘗試訪問SECTION_WITH_FILTER url時執行過濾器。 這是我的代碼:Spring自定義篩選器在指定的URL上只執行1次

@Autowired 
MyFilter myFilter; 

@Override 
protected void configure(HttpSecurity http) throws Exception { 

    logger.debug("<CONFIGURE HTTPSECURITY/>"); 

    http 
      .authorizeRequests() 
      .antMatchers("/login*.*", "/error.*", "/resources/**", "/javax**/**").permitAll() 
      .antMatchers("/SECTION_WITH_FILTER/**").permitAll() 
      .antMatchers("/", "/*.jsf", "/**/*.jsf", "/*.faces", "/**/*.faces").hasAnyRole("ADMIN") 
      .anyRequest().authenticated() 
      .and() 
      .formLogin() 
      .loginPage("/login.jsf") 
      .permitAll() 
      .and() 
      .logout() 
      .invalidateHttpSession(false) 
      .logoutSuccessUrl("/") 
      .deleteCookies("JSESSIONID") 
      .permitAll() 
      .and().csrf().disable(); 
    http 
      .addFilterBefore(myFilter, BasicAuthenticationFilter.class); 

} 

我的問題是,在過濾器啓動後,任何形式的網站的每一個提交。

我已經嘗試過了FilterRegistrationBean也用於設置過濾器僅當用戶進入一個特定的URL:

@Bean 
public FilterRegistrationBean filterRegistration() { 

    FilterRegistrationBean registration = new FilterRegistrationBean(); 
    registration.setFilter(myFilter); 
    registration.addUrlPatterns("/SECTION_WITH_FILTER/**"); 
    registration.setName("myFilter"); 
    registration.setEnabled(true); 
    return registration; 
} 

但使用這種方法StackOverflowError異常被拋出。

org.apache.catalina.core.StandardWrapperValve invoke 
GRAVE: Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Filter execution threw an exception] with root cause 
java.lang.StackOverflowError 
    at javax.servlet.http.HttpServletRequestWrapper.getSession(HttpServletRequestWrapper.java:231) 
    at org.apache.catalina.core.ApplicationHttpRequest.getSession(ApplicationHttpRequest.java:589) 
... 

我怎樣才能改變我的代碼,以使單個URL指定的過濾器,只啓動第一次用戶嘗試去實現它? 感謝

回答

2

您可以實現OncePerRequestFilter,覆蓋doFilterInternal方法做自己的生意,如果某些URL不應該過濾,您可以覆蓋shouldNotFilter方法。

此過濾器用於識別請求已被過濾。默認實現基於具體過濾器實例的已配置名稱。

相關問題