Spring Security配置中的单个角色多个IP地址 [英] Single role multiple IP addresses in Spring Security configuration

查看:833
本文介绍了Spring Security配置中的单个角色多个IP地址的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的Spring Boot项目中,我试图访问具有特定IP地址的多个管理员用户。

In my Spring Boot project I am trying to give access to several admin users with specific IP address.

是否可以将单个角色映射到多个IP地址?

以下是我的安全配置中的代码无效。 (为了简单起见,我给出了硬编码的角色名称和IP地址)

Here is the code from my security configuration which didn't work. (I am giving hard coded role name and ip addresses for simplicity)

@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
}

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

推荐答案

您的 for 循环导致以下配置:

Your for loop results in following configuration:

@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

only the first matcher is considered, see 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")


你必须建立类似的东西:

You have to build something like:

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'))";

这篇关于Spring Security配置中的单个角色多个IP地址的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆