2017-09-05 51 views
1

我想爲我的應用程序使用單獨的WebSecurityConfigurerAdapter爲每種類型的身份驗證配置多個身份驗證類型。多WebSecurityConfigurer適配器和篩選鏈

總體思路是使用WebSecurityConfigurerAdapter configure(HttpSecurity http)方法來匹配url模式,並使用專用專有過濾器(其中包括授權)完成所有身份驗證。

@Configuration 
@EnableWebSecurity 
public class DemoMultipleWebSecurityConfigurerAdapter { 

    @Order(1) 
    @Configuration 
    public static class BasicSecurityAdapter extends WebSecurityConfigurerAdapter { 

     @Override 
     public void configure(HttpSecurity http) throws Exception { 
      String endpointPattern = "/api/basic/**"; 
      http.requestMatchers().antMatchers(endpointPattern); 
      http.csrf().ignoringAntMatchers(endpointPattern); 
      http.authorizeRequests().antMatchers(endpointPattern).authenticated(); 


      http.addFilterBefore(new MyBasicAuthFilter(), LogoutFilter.class); 
     } 
    } 

    @Order(2) 
    @Configuration 
    public static class SSOSecurityAdapter extends WebSecurityConfigurerAdapter { 
     @Override 
     public void configure(HttpSecurity http) throws Exception { 
      String endpointPattern = "/api/sso/**"; 
      http.requestMatchers().antMatchers(endpointPattern); 
      http.csrf().ignoringAntMatchers(endpointPattern); 
      http.authorizeRequests().antMatchers(endpointPattern).authenticated(); 


      http.addFilterBefore(new MySSOAuthFilter(), LogoutFilter.class); 
     } 
    } 
} 

在初始化過程中,我可以看到每個WebSecurityConfigurerAdapter越來越HttpSecurity的不同實例配置(這是假設有自己的過濾器鏈),但是在運行時被調用的過濾器鏈始終是創建一個無論我調用哪個端點,都是第一個WebSecurityConfigurerAdapter。

根據文檔Spring應該使用HttpSecurity實例來找到正確的過濾器鏈來過濾(根據url模式)。

關於我在做什麼的錯誤? (我使用Spring 1.5.6-RELEASE來測試這個)

回答

1

你不需要多個WebSecurityConfigurerAdapter;只需配置篩選器,以便它們僅用於匹配URL模式。換句話說,添加所有的過濾器,但是使過濾器有條件地工作。

+0

這就是我最終做的事情(使用Spring使用的相同匹配組件來路由到Spring中註冊的Filter中的相應Filter)。 –