2017-06-01 160 views
1

在我的Spring Boot項目中,我嘗試訪問具有特定IP地址的多個管理員用戶。Spring Security配置中的單角色多個IP地址

是否可以將單個角色映射到多個IP地址?

這裏是我的安全配置中的代碼,它沒有工作。 (我給硬編碼的角色名和IP地址爲簡單起見)

@SuppressWarnings("ALL") 
@Configuration 
@EnableWebSecurity 
public class MyWebSecurityConfig extends WebSecurityConfigurerAdapter { 

    @Override 
    protected void configure(HttpSecurity http) throws Exception { 
     List<String> ipAddresses = new ArrayList<>(); 
     ipAddresses.add("127.0.0.1"); 
     ipAddresses.add("192.168.1.0/24"); 
     ipAddresses.add("0:0:0:0:0:0:0:1"); 

     for (String ip : ipAddresses) { 
      http.authorizeRequests(). 
        antMatchers("/admin" + "/**") 
        .access("hasRole('admin') and hasIpAddress('" + ip + "')"); 
     } 
    } 

    //some other configurations 
} 

URL我的要求:http://localhost:9595/admin/checkappeals/211

+1

我收到以下錯誤:HTTP狀態403次-message-描述訪問指定的資源已被禁止。 – user7244716

回答

2

for循環的結果如下配置:

@SuppressWarnings("ALL") 
@Configuration 
@EnableWebSecurity 
public class MyWebSecurityConfig extends WebSecurityConfigurerAdapter { 

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

     http 
      .authorizeRequests() 
       .antMatchers("/admin/**").access("hasRole('admin') and hasIpAddress('127.0.0.1')") 
       .antMatchers("/admin/**").access("hasRole('admin') and hasIpAddress('192.168.1.0/24')") 
       .antMatchers("/admin/**").access("hasRole('admin') and hasIpAddress('0:0:0:0:0:0:0:1')"); 
    } 

    //some other configurations 
} 

因此對於URL:

http://localhost:9595/admin/checkappeals/211 

僅被認爲是第一匹配,見HttpSecurity#authorizeRequests

Note that the matchers are considered in order. Therefore, the following is invalid because the first matcher matches every request and will never get to the second mapping:

http.authorizeRequests().antMatchers("/**").hasRole("USER").antMatchers("/admin/**") 
      .hasRole("ADMIN") 

你必須建立這樣的:

http 
    .authorizeRequests() 
     .antMatchers("/admin/**").acces("hasRole('admin') and (hasIpAddress('127.0.0.1') or hasIpAddress('192.168.1.0/24') or hasIpAddress('0:0:0:0:0:0:0:1'))"; 
+0

非常奇怪的一天,這已被張貼我有同樣的問題。你知道有什麼辦法讓這個作爲一個清單工作嗎?我的問題是,需要授權的IP地址數量未知(將從配置文件讀取),因此每個IP位於訪問參數內的解決方案不起作用。謝謝 – haddow64

+2

@ haddow64:使用StringBuilder(或類似的東西)並在for循環中協調條件。完整的條件使用像'antMatchers(「/ admin/**」).access(condition)'。 – dur