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

查看:39
本文介绍了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
}

我的请求的 URL: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")

您必须构建如下内容:

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天全站免登陆