2017-06-01 309 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