2016-09-19 154 views
1
@EnableWebSecurity 
public class MultiHttpSecurityConfig { 

@Configuration 
@Order(1) 
public static class App1ConfigurationAdapter extends WebSecurityConfigurerAdapter { 
    protected void configure(HttpSecurity http) throws Exception { 
     http.csrf().disable().authorizeRequests() 
     .antMatchers("/my/**", "/account/**").access("hasRole('ROLE_USER') or hasRole('ROLE_ADMIN')") 
     .and().formLogin().loginPage("/login"); 
    } 
} 

@Configuration 
@Order(2) 
public static class App2ConfigurationAdapter extends WebSecurityConfigurerAdapter { 
    @Override 
    protected void configure(HttpSecurity http) throws Exception { 
     http.csrf().disable().authorizeRequests() 
     .antMatchers("/admin/**").access("hasRole('ROLE_ADMIN')") 
     .and().formLogin().loginPage("/adminlogin"); 
    } 
} 
} 

這應該是兩種不同的登錄表單。我的問題是沒有顯示最高級別/ adminlogin的那個。我知道爲什麼?請幫忙。該代碼是從Spring boot - how to configure multiple login pages?春季開機和彈簧安全多登錄頁面

繼索菲亞的建議我嘗試這樣做:

@Configuration 
@Order(2) 
public static class UserConfigurationAdapter extends WebSecurityConfigurerAdapter { 
    @Override 
    protected void configure(HttpSecurity http) throws Exception { 
     http 
     .requestMatcher(new AntPathRequestMatcher("/my/**")) 
     .csrf().disable()  
     .authorizeRequests().antMatchers("/my/**").access("hasRole('ROLE_USER')") 
     .and().formLogin().loginPage("/login"); 
    } 
} 

@Configuration 
@Order(1) 
public static class AdminConfigurationAdapter extends WebSecurityConfigurerAdapter { 
    @Override 
    protected void configure(HttpSecurity http) throws Exception { 
     http 
     .requestMatcher(new AntPathRequestMatcher("/admin/**")) 
     .csrf().disable()  
     .authorizeRequests().antMatchers("/admin/**").access("hasRole('ROLE_ADMIN')") 
     .and().formLogin().loginPage("/adminlogin"); 
    } 
} 

但在這兩種情況下/登錄被稱爲

+0

當我進入例子http://docs.spring.io/spring- security/site/docs/current/reference/html/jc.html#multiple-httpsecurity我得到這個異常:java.lang.IllegalStateException:WebSecurityConfigurers上的@Order必須是唯一的。 100的順序已經用於... FormLoginWebSecurityConfigurerAdapter ... – ropo

回答

2

我認爲那爲什麼你的管理員登錄不啓動的原因是因爲:首先,它的優先級不高。

@Order定義了註釋組件的排序順序。 該值是可選的,表示Ordered界面中定義的訂單值。 較低的值具有較高的優先級。默認值是Ordered.LOWEST_PRECEDENCE,表示最低優先級(丟失任何其他指定的訂單值)。

其次,根據HttpSecurity的Javadoc中:

一個HttpSecurity類似於命名空間配置Spring Security的XML元素。它允許爲特定的http請求配置基於web的安全性。默認情況下,它將應用於所有請求,但可以使用requestMatcher(RequestMatcher)或其他類似的方法進行限制。

所以要儘量限制HttpSecurity對象來激活你的管理頁面首先配置requestMatcher這樣的:

http 
     .requestMatcher(new AntPathRequestMatcher("/admin/**")) 
     .csrf().disable()  
     .authorizeRequests().antMatchers("/admin/**").access("hasRole('ROLE_ADMIN')") 
     .and().formLogin().loginPage("/adminlogin");