Spring Security配置中的单角色多个IP地址

val*_*jon 2 java security ip-address spring-security spring-boot

在我的Spring Boot项目中,我试图授予具有特定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
}
Run Code Online (Sandbox Code Playgroud)

我的请求的网址:http:// localhost:9595 / admin / checkappeals / 211

小智 6

您可以通过以下方式将逗号分隔的 ip 连接到 .access() 方法的表达式中:

private String createHasIpRangeExpression() {

    String ipRanges= "127.0.0.1,192.168.1.0/24,0:0:0:0:0:0:0:1"
    List<String> validIps = Arrays.asList(ipRanges.split("\\s*,\\s*"));
    String hasIpRangeAccessExpresion = validIps.stream()
      .collect(Collectors.joining("') or hasIpAddress('", "hasIpAddress('","')"));
    return hasIpRangeAccessExpresion;
}
Run Code Online (Sandbox Code Playgroud)


dur*_*dur 5

您的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
}
Run Code Online (Sandbox Code Playgroud)

所以对于URL:

http://localhost:9595/admin/checkappeals/211
Run Code Online (Sandbox Code Playgroud)

仅考虑第一个匹配器,请参见HttpSecurity#authorizeRequests

注意匹配器是按顺序考虑的。因此,以下内容无效,因为第一个匹配器匹配每个请求,并且永远不会到达第二个映射:

http.authorizeRequests().antMatchers("/**").hasRole("USER").antMatchers("/admin/**")
            .hasRole("ADMIN")
Run Code Online (Sandbox Code Playgroud)

您必须构建类似:

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'))";
Run Code Online (Sandbox Code Playgroud)

  • @ haddow64:使用StringBuilder(或类似工具)并在for循环中添加条件。完整的条件使用如`antMatchers(“ / admin / **”)。access(condition)`。 (2认同)